我创建了一个扩展ImageView的类,允许我在触摸时在ImageView上绘制矩形。
我可以绘制矩形,但只有在我从起点向下和向右拖动矩形时才会显示。
如果我将矩形从起点向上或向左拖动,则不会绘制矩形。 OnDraw()会触发,但不会显示任何内容。
我的课程:
public class TagImageView extends ImageView {
private float downX;
private float downY;
private float upX;
private float upY;
private Paint paint;
public TagImageView(Context context) {
super(context);
init();
}
public TagImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TagImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
invalidate();
return true;
case MotionEvent.ACTION_MOVE:
upX = event.getX();
upY = event.getY();
invalidate();
return true;
case MotionEvent.ACTION_UP:
invalidate();
return true;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return super.onTouchEvent(event);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(downX, downY, upX, upY, paint);
}
}
编辑:不确定这是否相关? https://stackoverflow.com/a/24168545/2380071
答案 0 :(得分:0)
好吧,我刚刚修改了我的OnDraw()
方法来检查downX,downY和upX,upY点的值。琐碎,真的......虽然不确定它是否最有效率。欢迎任何建议(或者,呃..指针)!
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (downX < upX && downY < upY)
canvas.drawRect(downX, downY, upX, upY, paint);
else if (downX > upX && downY < upY)
canvas.drawRect(upX, downY, downX, upY, paint);
else if (downX < upX && downY > upY)
canvas.drawRect(downX, upY, upX, downY, paint);
else
canvas.drawRect(upX, upY, downX, downY, paint);
}