Scaling canvas and keeping center

Viewed 8485

I'm want to scale a canvas with a bitmap drawn on it. I'm able to scale the canvas but the bitmap drawn on it moves to the upper left respectively lower right.

@Override
protected void onDraw(Canvas canvas) {
    canvas.translate(mPosX, mPosY);
    canvas.scale(mScaleFactor, mScaleFactor);

    //draw bitmap
}

For the last few days I tried many different approaches from manipulating translation coordinates to pivot points for scaling. But nothing did work for me. I'm pretty sure there must be an easy solution for my problem.

Thanks in advance

2 Answers
var widthNew = ctx.canvas.width / 2;
var heightNew = ctx.canvas.height / 2;
ctx.setTransform(scale,0,0,scale,-(scale-1)*widthNew,-(scale-1)*heightNew);

This will help you scale the canvas horizontally and vertically with the horizontal and vertical translation.

Related