How to scale a bitmap drawn on a canvas while maintaining the rotation and translation given by a matrix
Bitmap # 1 is really large, about 2592 X 1456, but scaled down to fit the display-only device screen.
Then I painted the lips Bitmap (# 2) on the bitmap # 1 Canvas using a matrix (rotate, scale, translate) as shown above.
Exactly what I want to achieve is to keep a copy of the final bitmap scaled back to its original size (2592 x 1456).
I tried to achieve this by scaling the Bitmap # 1 matrix.
This is what I have tried so far:
// adjust the matrix to the original image size
// new matrix big
Matrix newMatrix = new Matrix();
// copy matrix from small matrix
newMatrix = matrix;
RectF src = new RectF(0,0,backgroundImage.getWidth(), backgroundImage.getHeight());
RectF dst = new RectF(0,0, origBackground.getWidth(), origBackground.getHeight());
newMatrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
canvas.drawBitmap(bitmap, newMatrix, paint);
My problem is that in the resulting bitmap # 1 the bitmap (# 2) is placed at x = 0 and y = 0, not the required coordinates, the rotation specified is missing.
source to share
For scaling it is better to use Canvas native methods save()
and restore()
.
See this answer .
For your purpose, use translate(x,y)
a drawing in certain coordinates, and rotate(deg,x,y)
to draw a certain angle of rotation, fixed in the specific coordinates.
Hope this helps to solve your problems.
source to share
After an hour of trying. Finally I got an answer. Below is the source code I used. Thanks to @xAF.
Greetings,
public Bitmap saveBitmap()
{
Bitmap bm = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(bm);
// draw the background photo with its original size
mCanvas.drawBitmap(bitmap1, 0, 0, null);
// put the lips and adjust the matrix to the original image size
Matrix newMatrix = new Matrix(); // new big matrix
// copy the screen small matrix (with rotate, scale, translation)
newMatrix.set(matrix);
float scaleWidth = ((float) bitmap1.getWidth()) / bitmap2.getWidth();
float scaleHeight = ((float) bitmap1.getHeight()) / bitmap2.getHeight();
newMatrix.postScale(scaleWidth, scaleHeight, 0, 0);
mCanvas.drawBitmap(bitmapLips, newMatrix, paint);
return bm;
}
source to share