web-dev-qa-db-fra.com

Retourner une image bitmap horizontalement ou verticalement

En utilisant ce code, nous pouvons faire pivoter une 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);
}

Mais comment pouvons-nous retourner une image horizontalement ou verticalement?

15
activity

cx,cy étant le centre de l'image:

Retourner dans x:

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

Flip dans y:

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

Extension courte pour 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)
}

Et utilisation:

Pour le retournement horizontal: -

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

Pour le retournement vertical: -

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

Pour 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)
}
1
Kit Mak