Search code examples
javaandroidtouch-eventondraw

Drawing rectangle on ImageView - not drawing upwards/leftwards


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


Solution

  • Well, I just ended up modifying my OnDraw() method to check the values of the downX, downY and upX, upY points. Trivial, really... although not sure if it's the most efficient. Welcome to any suggestions (or, er.. pointers)!

    @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);
    }