简体   繁体   中英

Flip a bitmap horizontally and draw to specific part of canvas

How do I draw this bitmap to the canvas in the exact same placement, but flipped horizontally? The matrix documentation is not exactly verbose. Here is the initial drawing:

canvas.DrawBitmap (_ballBmpRight, ParentView._ballX, ParentView._ballY, null);

My attempt to flip the bitmap:

flipHorizontalMatrix = new Matrix();
            flipHorizontalMatrix.SetScale(-1,1);
            flipHorizontalMatrix.PostTranslate(_ballBmpRight.Width, 0); 

Then draw it (this is where I cannot place it in the correct part of the canvas):

canvas.DrawBitmap (_ballBmpRight, flipHorizontalMatrix,  null);

I ended up doing this:

BitmapDrawable flip(BitmapDrawable d)
        {
            Matrix m = new Matrix();
            m.PreScale(-1, 1);
            Bitmap src = d.Bitmap;
            Bitmap dst = Bitmap.CreateBitmap(src, 0, 0, src.Width, src.Height, m, false);
            //dst.SetDensity(DisplayMetrics.DENSITY_DEFAULT);
            return new BitmapDrawable(dst);
        }

Client code for flip:

var bd = new BitmapDrawable (_ballBmpRight);
            BitmapDrawable bdFlipped = flip (bd);
            _ballBmpLeft = bdFlipped.Bitmap;

Canvas drawing code:

canvas.DrawBitmap (_ballBmpLeft, ParentView._ballX, ParentView._ballY, null);

Please note the method names have varied slightly (.getBitmap() becomes just .Bitmap) as I am using Xamarin.Android.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM