2013-01-21 127 views
3

我有一個自定義的視圖,它在onDraw()的畫布上繪製一些位圖。該圖正在工作。看看代碼片段:Android:畫布不縮放

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 
    canvas.save(); 

    if(appInitialized) { 

     hsSide.draw(canvas); 
     scaleA.draw(canvas); 
     scaleB.draw(canvas); 

    } 
    canvas.scale(mScaleFactor, mScaleFactor, pivotX, pivotY); 
    canvas.restore(); 
} 

我已經實現了ScaleGestureListener,它在屏幕上應用了縮放縮放時縮放畫布。問題在於畫布不能縮放。如果我在if(appInitialized) {之前放canvas.scale(mScaleFactor, mScaleFactor, pivotX, pivotY);,它將縮放畫布,但在此之後,即hsSide.draw(canvas);不縮放。它採用正常的規模。 這裏有繪畫方法:

hsDide.draw:

@Override 
public void draw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    canvas.drawBitmap(mBitmap, canvas.getWidth()/2 - mBitmap.getWidth()/2, 0, null); 
} 

scaleA.draw:

@Override 
public void draw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    canvas.drawBitmap(mBitmap, canvas.getWidth()/2 - mBitmap.getWidth()/2, canvas.getHeight()/2 - mBitmap.getHeight()/2, null); 
} 

scaleB.draw:

@Override 
public void draw(Canvas canvas) { 
    // TODO Auto-generated method stub 

    canvas.save(); 
    mMatrix.setRotate(currentAngle, canvas.getWidth()/2, canvas.getHeight()/2); 
    canvas.setMatrix(mMatrix); 
    canvas.drawBitmap(mBitmap, canvas.getWidth()/2 - mBitmap.getWidth()/2, canvas.getHeight()/2 - mBitmap.getHeight()/2, null); 
    canvas.restore(); 
} 

任何想法,我要去錯了... ???

回答

4

看着你的代碼infact,你應該在繪製之前縮放畫布,然後在繪製之後恢復它。因此,請按如下方式移動您的畫布比例:

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 
    canvas.save(); 

    canvas.scale(mScaleFactor, mScaleFactor, pivotX, pivotY); // MOVED HERE. 

    if(appInitialized) { 

     hsSide.draw(canvas); 
     scaleA.draw(canvas); 
     scaleB.draw(canvas); 

    } 

    canvas.restore(); 
} 

然後,您將繪圖大小放在畫布大小上。因此,當您縮放畫布時,仍然將其繪製爲完整尺寸,然後調整爲正常尺寸。因此沒有得到任何效果。

你需要做的是將畫布尺寸爲之前縮放,然後傳遞給你的繪製方法。然後使用這些尺寸在畫布上繪製。