Khawar Raza
Khawar Raza

Reputation: 16120

Android: Canvas not scaling

I have a custom View which draw some bitmaps on canvas in onDraw(). The drawing is working. 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 which scale the canvas when pinch zoom is applied on screen. The problem is that canvas is not scaling. 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 scaling. It draws on its normal scale. Here are draw 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...???

Upvotes: 3

Views: 5622

Answers (1)

IAmGroot
IAmGroot

Reputation: 13855

Looking at your code infact, you should scale the canvas before drawing onto it, then restore it once drawn. So move your canvas scale as follows:

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

You are then basing the draw size on the canvas size. So when you scale the canvas, you are still drawing it to its entire size, then resizing back to normal size. Hence not getting any effect.

What you need do is take the canvas size BEFORE scaling, then pass this to your draw method too. Then use those sizes to draw onto canvas.

Upvotes: 4

Related Questions