Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to turn an image sideways or upside-down?

Tags:

android

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.

like image 651
VJ Vélan Solutions Avatar asked Jul 23 '12 09:07

VJ Vélan Solutions


1 Answers

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);
}
like image 54
Aleks G Avatar answered Oct 04 '22 15:10

Aleks G