Search code examples
c#androidxamarinxamarin.androidzxing

Bitmap rotation in Xamarin.Android


How do you rotate Bitmap by 90 degrees in Xamarin.Android? I am using ZXing.Net.Mobile, C#/.NET Barcode Scanning Library and would like to print barcode vertically. Thanks in advance.


Solution

  • Once you have the barcode bitmap:

    var barcodeWriter = new ZXing.Mobile.BarcodeWriter
    {
        Format = ZXing.BarcodeFormat.CODE_128,
        Options = new ZXing.Common.EncodingOptions
        {
            Width = 300,
            Height = 300
        }
    };
    
    var barcode = barcodeWriter.Write("ZXing.Net.Mobile");
    

    You can rotate it with this:

    var barcodeRotated = RotateImage(barcode, 90);
    

    Here's the function:

    private Bitmap RotateImage(Bitmap src, float degrees)
    {
        var matrix = new Matrix();
    
        matrix.PostRotate(degrees);
    
        return Bitmap.CreateBitmap(src, 0, 0, src.Width, src.Height, matrix, true);
    }
    

    Result:

    barcode rotated

    Hope this helps!