Search code examples
c#xamarin.formsskiasharp

Xamarin: How can I align a logo image in the center of a SkiaSharp Bitmap


I'm trying to align a logo in the middle of a SKBitmap.

Here is my code:

SKBitmap bmpResult = SKBitmap.Decode(imgByteArray);
bitmap.DrawBitmap(bmpResult, 0, 20);

I already tried with different images, but the result is the same.

I know that SkiaSharp has MeasureText, but, as it says, for text, not for image.

I tried to get my device width with DeviceDisplay.MainDisplayInfo.Width and divide by 2, but no result.

NOTE that, even if I get a exactly number to divide (for example: bitmap.DrawBitmap(bmpResult, DeviceDisplay.MainDisplayInfo.Width / 2, 20);), when I have different screen densities, the final result will be different, that is, align with one device, unalign with other.

Is anyone knows how can I fix it?


Solution

  • You could create two bitmaps(bitmap1, bitmap2). Draw the bitmap1 first and then draw the bitmap2. I make two bitmaps in center for your reference.

      public partial class Page8 : ContentPage
    {      
        SKBitmap bitmap1 = new SKBitmap();
        SKBitmap bitmap2 = new SKBitmap();
        public Page8()
        {
            InitializeComponent();
    
            bitmap1 = LoadBitmapResource(typeof(Page8), "App3.image.jpeg");
            bitmap2 = LoadBitmapResource(typeof(Page8), "App3.durian_64.png");       
    
            // Create the SKCanvasView and set the PaintSurface handler
            SKCanvasView canvasView = new SKCanvasView();
            canvasView.PaintSurface += OnCanvasViewPaintSurface; ;
            Content = canvasView;
        }
    
        private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;
    
            canvas.Clear();
    
            float x1 = (info.Width - bitmap1.Width) / 2;
            float y1 = (info.Height - bitmap1.Height) / 2;
    
            float x2 = (info.Width - bitmap2.Width) / 2;
            float y2 = (info.Height - bitmap2.Height) / 2;
    
            canvas.DrawBitmap(bitmap1, x1, y1);
            canvas.DrawBitmap(bitmap2, x2, y2);
        }
        public static SKBitmap LoadBitmapResource(Type type, string resourceID)
        {
            Assembly assembly = type.GetTypeInfo().Assembly;
    
            using (Stream stream = assembly.GetManifestResourceStream(resourceID))
            {
                return SKBitmap.Decode(stream);
            }
        }
    
    }
    

    In the screenshot, you would see the bitmap2(green durian) in the center of the bitmap1.

    enter image description here