resize-image-on-xamarin

Let’s resize a Bitmap and UIImage with Xamarin…

Since the beginning of computers, developers has been struggled with Images. So did I with Xamarin 😉

So here I am sharing my findings on resizing a Bitmap and UIImage respectively on Android and iOS, meanwhile preserving the aspect ratio. I’m sharing this for the ease of fellow Xamarin devs, if anyone is struggling to find a source to find solution for both Xamarin Android and iOS platforms.

Xamarin Android

Alright here goes resizing of a Bitmap on Xamarin Android, and please note that I merely convered this implementation from Java to C# when I was implementing it in my project, and here’s the reference for it : http://stackoverflow.com/a/8224161

You need to pass in the height and width you need to resize your Bitmap into. Also as you can see this resizing method scales up the Bitmap on the Y Axis, and scaling begins from the center of the Image. 🙂

private Bitmap ResizeBitmap(Bitmap originalImage, int widthToScae, int heightToScale)
{
	Bitmap resizedBitmap = Bitmap.CreateBitmap(widthToScae, heightToScale, Bitmap.Config.Argb8888);

	float originalWidth = originalImage.Width;
	float originalHeight = originalImage.Height;

	Canvas canvas = new Canvas(resizedBitmap);

	float scale = this.Width / originalWidth;

	float xTranslation = 0.0f;
	float yTranslation = (this.Height - originalHeight * scale) / 2.0f;

	Matrix transformation = new Matrix();
	transformation.PostTranslate(xTranslation, yTranslation);
	transformation.PreScale(scale, scale);

	Paint paint = new Paint();
	paint.FilterBitmap = true;

	canvas.DrawBitmap(originalImage, transformation, paint);

	return resizedBitmap;
}

 

Xamarin iOS

So below is what I used for UIImage on iOS, which I was lucky enough to find through the Xamarin Forum: https://forums.xamarin.com/discussion/comment/175585/#Comment_175585 So kudos to the original post! 🙂

public UIImage ResizeUIImage(UIImage sourceImage, float widthToScale, float heightToScale)
{
	var sourceSize = sourceImage.Size;
	var maxResizeFactor = Math.Max(widthToScale / sourceSize.Width, heightToScale / sourceSize.Height);
	if (maxResizeFactor > 1) return sourceImage;
	var width = maxResizeFactor * sourceSize.Width;
	var height = maxResizeFactor * sourceSize.Height;
	UIGraphics.BeginImageContext(new CGSize(width, height));
	sourceImage.Draw(new CGRect(0, 0, width, height));
	var resultImage = UIGraphics.GetImageFromCurrentImageContext();
	UIGraphics.EndImageContext();
	return resultImage;
}

 

Well there you have it.

Enjoy! 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s