java 水平或垂直翻转位图图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36493977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flip a Bitmap image horizontally or vertically
提问by activity
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?
但是我们如何水平或垂直翻转图像呢?
回答by weston
Given cx,cy
is the centre of the image:
给定的cx,cy
是图像的中心:
Flip in x:
翻转 x:
matrix.postScale(-1, 1, cx, cy);
Flip in y:
翻转y:
matrix.postScale(1, -1, cx, cy);
回答by mahesh_babariya
Short extension for Kotlin
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)
回答by Kit Mak
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)
}
回答by Style-7
Horizontal and vertical flips for Bitmap bms (source).
位图 bms 的水平和垂直翻转(来源)。
Matrix matrix = new Matrix();
// for horizontal flip
matrix.setScale(-1, 1);
matrix.postTranslate( bms.getWidth(),0);
// for vertical flip
matrix.setScale( 1,-1);
matrix.postTranslate( 0, bms.getHeight());
Bitmap bm = Bitmap.createBitmap( bms, 0, 0, bms.getWidth(), bms.getHeight(), matrix, true);
回答by Gabe Sechan
Its all about the matrix you use. 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.
它完全与您使用的矩阵有关。要绕 x 轴翻转它,请使用 [[-1,0],[0, 1]]。对于 y 轴,使用 [[1,0],[0,-1]]。这里重要的是行列式的绝对值是 1,所以它不会缩放。而 - 基本上反转了给定轴周围的位置。