Reputation: 379
I have to rotate a bitmap of 180°. The problem is, that the bitmap is rotated but the position is different.
Without rotation it looks like this:
With rotation it looks like this:
Here is my code:
geste_Bitmap = gesture.toBitmap ( width, height, 100, Color.YELLOW );
Bitmap gedrehte_Geste = rotatePicture(geste_Bitmap, width, height, imageView);
// rotatePicture2(geste_Bitmap, imageView);
imageView.setImageBitmap(gedrehte_Geste);
private Bitmap rotatePicture(Bitmap bitmapOrg, int width, int height, ImageView imageView){
int viewWidth = imageView.getMeasuredWidth();
int viewHeight = imageView.getMeasuredHeight();
float px = viewWidth/2;
float py = viewHeight/2;
Matrix matrix = new Matrix();
matrix.postTranslate(-bitmapOrg.getWidth() / 2, -bitmapOrg.getHeight() / 2);
matrix.postRotate(180);
matrix.postTranslate(px, py);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
return rotatedBitmap;
}
I changed my code to following, because px
and py
was 0 but changed nothing:
private void rotatePicture(final Bitmap bitmapOrg, final int width, final int height, final ImageView imageView){
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int viewWidth = imageView.getMeasuredWidth();
int viewHeight = imageView.getMeasuredHeight();
float px = viewWidth / 2;
float py = viewHeight / 2;
Log.d("px", "px " + px + "|" + py + bitmapOrg.getWidth());
Matrix matrix = new Matrix();
matrix.postTranslate(-px, -py);
matrix.postTranslate(-bitmapOrg.getWidth() / 2, -bitmapOrg.getHeight() / 2);
matrix.postRotate(180);
matrix.postTranslate(bitmapOrg.getWidth() / 2, bitmapOrg.getHeight() / 2);
matrix.postTranslate(px, py);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
imageView.setImageBitmap(rotatedBitmap);
return true;
}
});
}
Thanks a lot
Upvotes: 1
Views: 352
Reputation: 3777
Try this:
Matrix matrix = new Matrix();
matrix.postRotate(180, bitmapOrg.getWidth() / 2, bitmapOrg.getHeight() / 2);
matrix.postTranslate(px, py);
Upvotes: 1