Flip a Bitmap image horizontally or vertically

activity picture activity · Apr 8, 2016 · Viewed 18.6k times · Source

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?

Answer

weston picture weston · Apr 8, 2016

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