I've created a class which extends the ImageView allowing me to draw rectangles onto the ImageView on touch.
I can draw rectangles however they only display when I'm dragging the rectangle from the starting point downward and to the right.
If I drag the rectangle from the starting point upwards or to the left then no rectangle is drawn. OnDraw() fires but nothing displays.
My class:
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);
}
}
Edit: Not sure if this is relevant? https://stackoverflow.com/a/24168545/2380071