Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android canvas.scale(-1,1)

So my aim is to flip an image horizontally then draw it on a canvas. Currently I'm using canvas.scale(-1,1) which effectively works and draws the image horizontally, however it also screws with the x axis values where before the scale the x position would be 150 and after I'd have to switch it to -150 to render in the same spot.

My question is, how can I make it so the x value is 150 in both cases without having to adjust the x position after the scale? Is there a more effective way to do this without taking a hit on performance?

like image 300
methodin Avatar asked Oct 11 '10 00:10

methodin


2 Answers

I know this question is old, but I happened to bump into the same problem. In my situation, I had to flip the canvas when drawing on a class extending an ImageButton. Fortunately, the solution for this specific case was more elegant than I thought. Simply override the onDraw(Canvas) method as follows:

@Override
protected void onDraw(final Canvas canvas) {

    // Scale the canvas, offset by its center.
    canvas.scale(-1f, 1f,
        super.getWidth() * 0.5f, super.getHeight() * 0.5f);

    // Draw the button!
    super.onDraw(canvas);
}
like image 108
Japtar Avatar answered Oct 22 '22 11:10

Japtar


I've fixed this by applying the transformation to the bitmap prior to ever using it like this:

public void applyMatrix(Matrix matrix) {
    mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, 
      mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
}
...
Matrix matrix = new Matrix();
matrix.preScale(-1, 1);
mSprite.applyMatrix(matrix);
like image 22
methodin Avatar answered Oct 22 '22 10:10

methodin