移动画布矩形触摸问题(rect的中心)

时间:2014-09-05 02:22:42

标签: android android-canvas

我有一个代码,用户可以在屏幕上移动透明矩形。

我面临的问题是矩形当我拖动时从左上角移动作为枢轴,而我希望它从中心枢轴移动

示例

enter image description here

@Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

        case MotionEvent.ACTION_DOWN: {

            X = (int) ev.getX();
            Y = (int) ev.getY();
            invalidate();

            break;
        }

        case MotionEvent.ACTION_MOVE: {

            X = (int) ev.getX();
            Y = (int) ev.getY();
            invalidate();
            break;

        }

        case MotionEvent.ACTION_UP:

            break;

        }
        return true;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        // draw background
        canvas.drawBitmap(bgr, 0, 0, null);
        // copy the default overlay into temporary overlay and punch a hole
        // in it
        c2.drawBitmap(overlayDefault, 0, 0, null); // exclude this line to
                                                    // show all as you draw

        c2.drawRoundRect(new RectF(X, Y, X+350, Y+350), (float)20.0, (float)20.0, pTouch);
        // draw the overlay over the background
        canvas.drawBitmap(overlay, 0, 0, null); 
    }

1 个答案:

答案 0 :(得分:0)

@覆盖     public boolean onTouchEvent(MotionEvent ev){

    switch (ev.getAction()) {

    case MotionEvent.ACTION_DOWN: {

        X = (int) ev.getX();
        Y = (int) ev.getY();
        invalidate();

        break;
    }

    case MotionEvent.ACTION_MOVE: {

        X = (int) ev.getX();
        Y = (int) ev.getY();
        invalidate();
        break;

    }

    case MotionEvent.ACTION_UP:

        break;

    }
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.TRANSPARENT);
    // draw background
    canvas.drawBitmap(bgr, 0, 0, null);
    // copy the default overlay into temporary overlay and punch a hole
    // in it
    c2.drawBitmap(overlayDefault, 0, 0, null); // exclude this line to
                                                // show all as you draw

    c2.drawRoundRect(new RectF(X-175, Y-175, X+175, Y+175), (float)20.0, (float)20.0, pTouch);
    // draw the overlay over the background
    canvas.drawBitmap(overlay, 0, 0, null); 
}

虽然我要做的是创建一个具有rect和中心点值的对象,这样我就可以实现一个方法来检查我是否触摸了一个矩形然后如果是的话我可以移动它。您的代码所做的是将矩形移动到您触摸的屏幕中的任何位置。