0

我在创建一个绘制 Rectangle 并可以通过其角重新调整大小的 CustomView 时遇到问题。

以下是我的代码。

public class CustomView extends View {
    Canvas canvas;
    private Context mContext;
    private Rect rectObj;
    private Paint rectPaint;
    private Matrix transform;
    public CustomView(Context context) {
        super(context);
        mContext = context;
        initView();
    }
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }
    public CustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void initView() {
        rectPaint = new Paint();
        rectPaint.setColor(Color.parseColor("#55000000"));

        setFocusable(true); // necessary for getting the touch events
        canvas = new Canvas();
        // setting the start point for the balls

        rectObj = new Rect(100, 100, 200, 200);

        // Create a matrix to do rotation
        transform = new Matrix();
    }

    @Override
    public void onDraw(Canvas canvas) {
        // This is an easy way to apply the same transformation (e.g.
        // rotation)
        // To the complete canvas.
        canvas.setMatrix(transform);

        // With the Canvas being rotated, we can simply draw
        // All our elements (Rect and Point)
        canvas.drawRect(rectObj, rectPaint);
    }
}

当我运行这个程序时,会出现以下输出。

在此处输入图像描述

如图所示,我的“矩形”的左上角100,100,但是当我在屏幕上触摸“矩形的左上角”时,xy150,76或与原始绘图不匹配的东西。

我必须使用canvas.setMatrix(transform)在下一阶段旋转该矩形。
这段代码出了什么问题?

4

1 回答 1

1

在该方法onDraw(Canvas canvas)中,您应该做的一件事是调用该方法super.onDraw(cavas),然后不要执行“canvas.setMatrix(transform);” 你应该做'canvas.concat(transform);' Matrix因为画布有一个保存了一些值的初始值。此外,如果您只需要旋转或平移该矩形,您可以旋转和平移画布canvas.rotate(degree),例如。

于 2013-05-15T08:14:54.367 回答