I am trying to sale a bitmap and translating it at each step.
If we look at the following code, I am drawing an image, translating and scaling it and then performing the same operations in reverse so as to get the original configuration back. But after applying the operations, I do get the original scaled image (scale factor 1) but the image is translated t a different position.
Could you please point out the correct method do so ? (In the example above, how do I reach the original configuration? )
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Matrix matrix = new Matrix();
scale = (float)screenWidth/201.0f;
matrix.setTranslate(-40, -40);
matrix.setScale(scale, scale);
canvas.drawBitmap(bitMap, matrix, paint);
//back to original
canvas.drawColor(0, Mode.CLEAR);
matrix.setScale(1.0f/scale, 1.0f/scale);
matrix.setTranslate(40,40);
canvas.drawBitmap(bitMap, matrix, paint);
}
You should just use the Canvas
methods for scaling and translating, that way you can then take advantage of the save()
and restore()
APIs to do what you need. For example:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Save the current state of the canvas
canvas.save();
scale = (float) screenWidth / 201.0f;
canvas.translate(-40, -40);
canvas.scale(scale, scale);
canvas.drawBitmap(bitMap, 0, 0, paint);
//Restore back to the state it was when last saved
canvas.restore();
canvas.drawColor(0, Mode.CLEAR);
canvas.drawBitmap(bitMap, 0, 0, paint);
}
I think the problem with your original code might be because of the way scale and translate use the point around which you scale/translate. IF you specify the correct pivot points in between/for the operations, things will be ok.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With