By using this code we can rotate an image:
public static Bitmap RotateBitmap(Bitmap source, float angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); }
But how can we flip an image horizontally or vertically?
To flip it around the x axes, use [[-1,0],[0, 1]]. For the y axes, use [[1,0],[0,-1]]. The important thing here is that the absolute value of the determinant is 1, so it won't scale. And the - basically inverses the location around the given axes.
To flip an image or icon, simply: Select the object you would like to flip. Right click on that object, and select 'Flip Horizontal' or 'Flip Vertical'.”
You can flip the image, or turn it over like a card, by using the Flip Horizontally or Flip Vertically commands. These commands work on the whole image. To flip a selection, use the Flip Tool. To flip a layer, use the functions of the Layer → Transform menu or the Flip Tool.
Given cx,cy
is the centre of the image:
Flip in x:
matrix.postScale(-1, 1, cx, cy);
Flip in y:
matrix.postScale(1, -1, cx, cy);
Altogether:
public static Bitmap createFlippedBitmap(Bitmap source, boolean xFlip, boolean yFlip) { Matrix matrix = new Matrix(); matrix.postScale(xFlip ? -1 : 1, yFlip ? -1 : 1, source.getWidth() / 2f, source.getHeight() / 2f); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); }
Short extension for Kotlin
private fun Bitmap.flip(x: Float, y: Float, cx: Float, cy: Float): Bitmap { val matrix = Matrix().apply { postScale(x, y, cx, cy) } return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true) }
And usage:
For horizontal flip :-
val cx = bitmap.width / 2f val cy = bitmap.height / 2f val flippedBitmap = bitmap.flip(-1f, 1f, cx, cy) ivMainImage.setImageBitmap(flippedBitmap)
For vertical flip :-
val cx = bitmap.width / 2f val cy = bitmap.height / 2f val flippedBitmap = bitmap.flip(1f, -1f, cx, cy) ivMainImage.setImageBitmap(flippedBitmap)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With