2013-01-05 57 views
6

我在我的主类有一个位图对象。我需要将此位图发送到我的自定义视图类,以将其设置为画布上进一步处理的背景。如何在我的自定义视图的画布中设置位图图像?

例如,有一种称为setPicture的方法,它接收位图作为参数。那么,如何在画布上绘制这个位图呢?

请参阅下面的代码:

public class TouchView extends View { 

final int MIN_WIDTH = 75; 
final int MIN_HEIGHT = 75; 
final int DEFAULT_COLOR = Color.RED; 
int _color; 
final int STROKE_WIDTH = 2; 

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
private float x, y; 
private boolean touching = false; 

public TouchView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

public TouchView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

public TouchView(Context context) { 
    super(context); 
    // TODO Auto-generated constructor stub 
    init(); 
} 

private void init() { 
    setMinimumWidth(MIN_WIDTH); 
    setMinimumHeight(MIN_HEIGHT); 
    _color = DEFAULT_COLOR; 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    // TODO Auto-generated method stub 
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), 
      MeasureSpec.getSize(heightMeasureSpec)); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 

    if (touching) { 
     paint.setStrokeWidth(STROKE_WIDTH); 
     paint.setColor(_color); 
     paint.setStyle(Paint.Style.FILL); 
     canvas.drawCircle(x, y, 75f, paint); 
    } 
} 

public void setPicture (Bitmap bitmap) { 

     /////// 
     This method must receive my bitmap to draw it on canvas!!!!!!!!!!!!!!! 
     /////// 


} 

public void setColor(int color) { 
    _color = color; 
} 

@Override 
public boolean onTouchEvent(MotionEvent motionEvent) { 
    // TODO Auto-generated method stub 

    switch (motionEvent.getAction()) { 
    case MotionEvent.ACTION_MOVE: 
    case MotionEvent.ACTION_DOWN: 
     x = motionEvent.getX(); 
     y = motionEvent.getY(); 
     touching = true; 
     break; 
    default: 
     touching = false; 
    } 
    invalidate(); 
    return true; 
} 

}

我应该如何发送此位图的OnDraw?

回答

6

里面你onDraw()方法,

只是做

canvas.drawBitmap(myBitmap, 0, 0, null); 

MYBITMAP是您的位图的变量。

0,0指的是绘制在左上角的坐标。

还有其他可用的API,来绘制到某些区域等

More info can be found here in the api docs.

或者: 代替延伸ImageView的,并使用setImageBitmap(Bitmap src);方法实现这一目标。

+2

Doomsknight,非常感谢!它的作品,你让我的一天! :)) – Carlos

+0

我认为这个问题是如何将myBitmap变量从MainActivity获取到自定义视图。在你的答案中,myBitmap将是未定义的。 – Donato

+0

@Donato我想我看到他在绘制图像时比将图像传递给自定义视图更麻烦。只需创建一个设置参考位图/ ID的方法,或者将其作为参数添加到构造函数中。 – Doomsknight

0

将位图转换为drawable并使用View类的setBackgroundDrawable方法。

public void setPicture (Bitmap bitmap) { 
    setBackgroundDrawable(new BitmapDrawable(bitmap)); 
} 
+0

Leonidos,谢谢你也可以,但我注意到这种方法延伸图片以适应组件。是否可以看到我的照片在实际尺寸或正确的比例? – Carlos

+0

是的,例如,将BitmapDrawable的引力设置为“顶部”。阅读有关BitmapDrawable的文档。它有很多功能。 – Leonidos

相关问题