Less is more!

Hey everyone,

Ever tried adding a library component that you’ve found through either GitHub or the Xamarin store? How many are there also to begin with?

Also, how portable will the component be? Will it work on just one platform or will it work on all?

Let’s take image library components for example. Fresco is quite a nice image library that immensely helps manage images in our memory buffer, so that there is no need to do a lot of processing on the client-side developer’s end. However, this is only for Android, and Xamarin does not yet have this component in their store 🙁

But no worries. SkiaSharp is here to the rescue! It is cross-platform and has been implemented by Google that Xamarin has ported over!

There is a nice introduction on how to get started. It is quite comprehensive in each of its functionality, but to get started is not as smooth as how Fresco’s documentation, which is to go from adding the gradle dependency down towards the implementation, would be. Its guide is okay-ish if one knows where to look, so that’s not too much of a problem. There’s an exception to one thing however.

What is it?!

The image management on where to load its buffers in memory! What if we had a large image and tried to put it on a canvas with all of the information? Our application will crash with an OutOfMemoryException! 🙁

How do we rectify this?

The easiest solution would be to call the .Resize(SKImageInfo, SKBitmapResizeMethod) method on a SKBitmap object. To do this, we’ll also need an SKImageInfo providing the desired width and height that we want to display on our device in the app.

Let’s say that if we want our image to be 1/2 the width of the screen, we can make our width to be context.Resources.DisplayMetrics.WidthPixels / 2. If we want our height to match the dimensions of how the image should look like, then it should be image.Width * width / image.Height, where image is our SKBitmap object.

Therefore, our code should look like this:

SKBitmap resizedSkBitmap;
using (var largeSkBitmap = SKBitmap.Create("ourLargeImage.png"))
{
    var width = context.Resources.DisplayMetrics.WidthPixels / 2;
    var height = largeSkBitmap.Width * width / largeSkBitmap.Height;
    var wantedImageInfo = new SKImageInfo(width, height);
    resizedSkBitmap = largeSkBitmap.Resize(wantedImageInfo, SKBitmapResizeMethod.Lanczos3);
}


Use the resize method that would suit your needs best 😉 I’ll provide the link here.

That’s pretty much it!

Also, don’t forget to call resizedSkBitmap.Dispose(); when finished with the image to avoid any memory leaks 😉

Until next time!

Brian.