我扩展了View以使用canvas。我在onDraw()方法中绘制基本绘图,当用户在画布中触摸时我必须在那里绘制图像,因为我在onTouchEvent()方法中使用了canvas,它没有在那里绘制任何东西,代码如下,问题是什么?如何解决这个问题
public class ScreenView extends View(){
static Canvas canvas;
Bitmap bm;
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
bm = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
canvas.draw.......
......
...........
}
public boolean onTouchEvent(final MotionEvent event) {
handleTouches(event.getX(), event.getY());
return false;
}
public void handleTouches(float x, float y) {
xLocTouch = (int) x;
yLocTouched = (int) y;
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawBitmap(bm, xLocTouch ,yLocTouched , paint);
}
}
答案 0 :(得分:0)
您应该在invalidate()
内调用onTouchEvent
方法,然后调用onDraw()
方法,并且您应该存储x
和y
坐标,然后将位图绘制到此坐标,如下所示:
public class ScreenView extends View {
int xLocTouched;
int yLocTouched;
Bitmap bm;
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
bm = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
//your basic drawings also should depends on xLocTouched and yLocTouched.
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawBitmap(bm, xLocTouched ,yLocTouched , paint);
}
public boolean onTouchEvent(final MotionEvent event) {
xLocTouched = (int) event.getX();
yLocTouched = (int) event.getY();
invalidate();
return false;
}
}