问题
Sample Image
Hi everyone. I am new to Image manipulation in android using matrix. I am working on an app which displays Bitmap #1 on the screen of the device.
Bitmap #1 is really big, about 2592 X 1456, but scaled down to fit the screen size of the device for displaying purposes only.
Then I have drawn the lips Bitmap (#2) on Bitmap #1 Canvas, using matrix (with rotate, scale, translation), as image above is showing.
Precisely what I want to achieve is to save a copy of the final Bitmap, scaled backwards to the original size (2592 x 1456).
I tried to achieve it by scaling Bitmap #1 matrix.
This is what I've 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, lips Bitmap (#2) is being placed at the x=0 and y=0 and not at the required coordinates, missing specified rotation.
回答1:
For scaling purposes the better option is to use Canvas own save()
and restore()
methods.
See this answer.
For your purpose use translate(x,y) to draw at specific coordinates and rotate(deg,x,y) to draw at specific rotation angle pinned at specific coordinates.
Hope this would help solve your issues.
回答2:
After an hour of trying. I finally got the answer. Below is the source code that I've been using. Thanks to @xAF.
Cheers,
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;
}
来源:https://stackoverflow.com/questions/35678175/how-to-scale-bitmap-drawn-on-the-canvas-while-saving-rotation-and-translation-sp