Scaling matrix transformed images for Compositing
I'm setting up a camera view where it has a image view over the top of it and uses matrix transforms to move the image around the screen. When I take the photo I want to be able to composite the image onto the photo with correct respect to location and scaling. The photo is only ever portrait and is rotated if it's landscape.
public void onPictureTaken(byte[] data, Camera camera) {
BitmapFactory.Options opt = new BitmapFactory.Options();
this.newPhoto = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
int photoWidth = newPhoto.getWidth() > newPhoto.getHeight()?newPhoto.getHeight():newPhoto.getWidth();
int photoHeight = newPhoto.getWidth开发者_如何学编程() > newPhoto.getHeight()?newPhoto.getWidth():newPhoto.getHeight();
//Preview is fullscreen
Display display = getWindowManager().getDefaultDisplay();
int previewWidth = display.getWidth();
int previewHeight = display.getHeight();
float scale = (float)photoHeight / (float)previewHeight;
float scaleX = (float)photoWidth / (float)previewWidth;
Bitmap finished = Bitmap.createBitmap(photoWidth, photoHeight, newPhoto.getConfig());
//Create canvas and draw photo into it
//[snip]
//Draw character onto canvas
int imageResource = getResources().getIdentifier(character + "large", "drawable", getPackageName());
if (imageResource != 0) {
Bitmap character = BitmapFactory.decodeResource(this.getResources(), imageResource);
RectF rect = new RectF();
float[] values = new float[9];
matrix.getValues(values);
rect.left = values[Matrix.MTRANS_X] * scaleX;
rect.top = values[Matrix.MTRANS_Y] * scale;
//273x322 WidthxHeight of preview character image
rect.right = rect.left + (273 * values[Matrix.MSCALE_X]) * scale;
rect.bottom = rect.top + (322 * values[Matrix.MSCALE_Y]) * scale;
//Logging here
canvas.drawBitmap(character, null, rect, null);
character.recycle();
}
System.gc();
newPhoto = finished;
showDialog(DIALOG_PHOTO_RESULT);
}
Logs:
Preview:480x854 Photo:1536x2048
Scale:2.3981264
Matrix:(112.45,375.85) scale:(1.00,1.00)
Rect:(359.8342,901.34326) w:654.6885 h:772.1968
The image rect doesn't seem to be scaling large enough as the resulting composite image has the character too far towards top/left and too small.
The problem was that android was pre-scaling the character images which threw out all my scale calculations
By moving the character images into the drawable-nodpi
folder I was able to stop android scaling the images for device so that the images can be scaled to match the camera views.
精彩评论