2013-05-15 35 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