I have a custom view and i am using onDraw() to draw onto my canvas. I am drawing an image on this canvas.
I want to turn the image upside down kinda like flip on a horizontal line as a reference. This is not the same as rotating the image by 180 deg or -180 deg.
Likewise, i want to mirror or flip sidways i.e with a vertical line as it's pivot or reference. Again this is not the same as the canvas.rotate() provides.
I am wondering how to do it. Should i use a matrix or does canvas provide any method to do it like that of a "rotate".
Thanks.
You cannot do it with Canvas directly. You will need to actually modify the Bitmap (using Matrix) before drawing it. Luckily, it's a very simple code to do this:
public enum Direction { VERTICAL, HORIZONTAL };
/**
Creates a new bitmap by flipping the specified bitmap
vertically or horizontally.
@param src Bitmap to flip
@param type Flip direction (horizontal or vertical)
@return New bitmap created by flipping the given one
vertically or horizontally as specified by
the <code>type</code> parameter or
the original bitmap if an unknown type
is specified.
**/
public static Bitmap flip(Bitmap src, Direction type) {
Matrix matrix = new Matrix();
if(type == Direction.VERTICAL) {
matrix.preScale(1.0f, -1.0f);
}
else if(type == Direction.HORIZONTAL) {
matrix.preScale(-1.0f, 1.0f);
} else {
return src;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With