水平或垂直翻转位图图像

act*_*ity 19 java android image matrix android-bitmap

通过使用此代码,我们可以旋转图像:

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);
}
Run Code Online (Sandbox Code Playgroud)

但是我们如何水平或垂直翻转图像?

wes*_*ton 44

给定cx,cy是图像的中心:

翻转x:

matrix.postScale(-1, 1, cx, cy);
Run Code Online (Sandbox Code Playgroud)

翻转y:

matrix.postScale(1, -1, cx, cy);
Run Code Online (Sandbox Code Playgroud)

  • @MayurRokade`source.getWidth()/ 2f`` source.getHeight()/ 2f` (6认同)

小智 14

使用 Kotlin 和扩展函数:

// To flip horizontally:
fun Bitmap.flipHorizontally(): Bitmap {
    val matrix = Matrix().apply { postScale(-1f, 1f, width / 2f, height / 2f) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

// To flip vertically:
fun Bitmap.flipVertically(): Bitmap {
    val matrix = Matrix().apply { postScale(1f, -1f, width / 2f, height / 2f) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
Run Code Online (Sandbox Code Playgroud)


i_m*_*hii 6

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)
}
Run Code Online (Sandbox Code Playgroud)

和用法:

对于水平翻转:-

val cx = bitmap.width / 2f
val cy = bitmap.height / 2f
val flippedBitmap = bitmap.flip(-1f, 1f, cx, cy)
ivMainImage.setImageBitmap(flippedBitmap)
Run Code Online (Sandbox Code Playgroud)

对于垂直翻转:-

val cx = bitmap.width / 2f
val cy = bitmap.height / 2f
val flippedBitmap = bitmap.flip(1f, -1f, cx, cy)
ivMainImage.setImageBitmap(flippedBitmap)
Run Code Online (Sandbox Code Playgroud)