Flip a Bitmap image horizontally or vertically
For kotlin,
fun Bitmap.flip(): Bitmap {
val matrix = Matrix().apply { postScale(-1f, 1f, width/2f, width/2f) }
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
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)
Just use below codes
private fun setVerticalFlip() {
if (binding.imgReal.scaleX == 1.0f) {
binding.imgReal.scaleX = -1.0f
} else {
binding.imgReal.scaleX = 1.0f
}
}
private fun setHorizontalFlip() {
if (binding.imgReal.scaleY == 1.0f) {
binding.imgReal.scaleY = -1.0f
} else {
binding.imgReal.scaleY = 1.0f
}
}