2013-05-15 34 views
0

我在创建绘制矩形并可通过其角部重新调整大小的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); 
    } 
} 

当我运行这个程序时,输出如下。

enter image description here

如图像显示,我的“矩形”的左上角100,100但是当我触摸屏幕上的‘矩形的左上角’XY150,76或与原图不匹配的东西。

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

+0

矩形的左下角坐标是100即x​​我猜不是左上角的坐标。我不确定,但猜测。 – Raghunandan

回答

1

在方法onDraw(Canvas canvas)你应该做的一件事是调用方法super.onDraw(cavas),之后,而不是做'canvas.setMatrix(transform);'你应该做'canvas.concat(变形);'因为画布有一个初始的Matrix,保存了一些值。另外,如果您只需旋转或翻译该矩形,则可以通过执行canvas.rotate(degree)来旋转和平移画布。

+0

非常感谢你..你已经解决了我的问题。 :) –

+0

canvas.getMatrix()。postConcat(transform);方法不应用“变换”矩阵中所做的任何更改。我正在做“transform.setRotate(degrees,rectObj.exactCenterX(),rectObj.exactCenterY());”。并且在改变这个之后,它不是旋转矩形。 –

+0

旋转画布而不是矩阵,'canvas.rotate(degrees,rectObj.exactCenterX(),rectObj.exactCenterY());' – bogdan