我试图让用户使用触摸在我的imageview上绘制多个圆圈。到目前为止,我已经设法一次只绘制一个。我知道在调用invalidate()之后我必须存储触摸点并重绘每个圆圈,但是还没有想办法。
这是我的代码,如果有人能指出我要添加/更改的内容或者就如何实现这一点提出任何建议,我将非常感激:
public class ImageView1 extends ImageView {
public int x;
public int y;
ImageView1 img = (ImageView1) findViewById (R.id.imageView1);
public ImageView1(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
}
public boolean onTouchEvent(MotionEvent event){
x = (int) event.getX();
y = (int) event.getY();
return true;
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
Paint p = new Paint();
p.setAntiAlias(true);
p.setColor(Color.RED);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(1);
canvas.drawCircle(x, y, 20, p);
invalidate();
}
}
答案 0 :(得分:1)
我通常将指针位置信息收集到SparseArray
中,并将指针ID作为键;
private SparseArray<PointF> mPointers = new SparseArray<PointF>();
@Override
public boolean onTouchEvent(MotionEvent me) {
switch (me.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
int ai = me.getActionIndex();
PointF pt = new PointF(me.getX(ai), me.getY(ai));
mPointers.put(me.getPointerId(ai), pt);
return true;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
int pid = me.getPointerId(me.getActionIndex());
mPointers.remove(pid);
return true;
}
case MotionEvent.ACTION_MOVE: {
for (int i = 0; i < me.getPointerCount(); ++i) {
PointF pt = mPointers.get(me.getPointerId(i));
pt.set(me.getX(i), me.getY(i));
}
return true;
}
}
return false;
}
然后,为了渲染单独的触摸点,您可以迭代mPointers
个值。