Scaling and translating a bitmap in android

I am trying to sell a bitmap and translate it at every step.

If we look at the following code, I draw the image, translate it and scale it, and then perform the same operations in reverse order to return the original configuration. But after applying the operations, I get the original scaled image (scale factor 1), but the image is transferred to a different position.

Could you indicate the correct method? (In the example above, how do I get to 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); } 
+4
source share
2 answers

You should just use the Canvas methods to scale and translate, so you can use the save() and restore() APIs to do what you need. For instance:

 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); } 
+5
source

I think the problem with your source code may be due to the way the scale and translation use the point around which you scale / translate. If you specify the correct reference points between / for operations, everything will be fine.

+1
source

Source: https://habr.com/ru/post/978356/


All Articles