Android: canvas does not scale

I have a custom view that draws some bitmaps to the canvas in onDraw (). The drawing works. Take a look at the code snippet:

@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();
}

      

I have implemented a ScaleGestureListener that scales the canvas when scaling is applied to the screen. The problem is the canvas doesn't scale. if i put canvas.scale(mScaleFactor, mScaleFactor, pivotX, pivotY);

before if(appInitialized) {

it scales the canvas but after it the drawing i.e. hsSide.draw(canvas);

is not scalable. It rests on its normal scale. Here are the drawing methods:

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();
}

      

Any idea where I am going wrong ... ???

+3


source to share


1 answer


Looking at your infact code, you have to scale the canvas before drawing on it and then restore it after painting. So move the canvas scale like this:

@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();
}

      



Then you base the draw size on the canvas size. So when you scale the canvas, you still paint it full size and then resize it back to normal size. Therefore, no effect is obtained.

What you need to do is take the canvas size BEFORE and then pass that to the paint method too. Then use those dimensions to paint on canvas.

+4


source







All Articles