我的主类中有一个Bitmap对象.我需要将此位图发送到我的自定义视图类,以将其设置为在画布上进一步处理的背景.
例如,有一个名为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?
解决方法
在你的onDraw()方法里面,
做就是了
- canvas.drawBitmap(myBitmap,null);
myBitmap是你的位图变量.
0,0指的是绘制的坐标,即左上角.
还有其他的Apis,可以吸引到某些地区等.
More info can be found here in the api docs.
或者:改为扩展ImageView,并使用setImageBitmap(Bitmap src);实现这一目标的方法.