水平或垂直翻转位图图像

2022-09-01 09:19:03

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

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);
}

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


答案 1

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

翻转 x:

matrix.postScale(-1, 1, cx, cy);

翻转 y:

matrix.postScale(1, -1, cx, cy);

完全:

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);
}

答案 2

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)
}

用法:

对于水平翻转:-

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

对于垂直翻转:-

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

推荐