在 ImageView 上绘制矩形 - 不绘制 upwards/leftwards

Drawing rectangle on ImageView - not drawing upwards/leftwards

我创建了一个 class,它扩展了 ImageView,允许我在触摸时在 ImageView 上绘制矩形。

我可以绘制矩形,但它们仅在我从起点向下并向右拖动矩形时才会显示。

如果我从起点向上或向左拖动矩形,则不会绘制矩形。 OnDraw() 触发但不显示任何内容。

我的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);
    }
}

编辑:不确定这是否相关?

好吧,我刚刚修改了 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);
}