Skip to content

Instantly share code, notes, and snippets.

@Digitalchemy
Created March 1, 2011 02:26
Show Gist options
  • Save Digitalchemy/848487 to your computer and use it in GitHub Desktop.
Save Digitalchemy/848487 to your computer and use it in GitHub Desktop.
Scale a UIImage to fill both dimensions of the specified cropRect
public UIImage ScaleImageToFillCropRect(UIImage image, RectangleF cropRect)
{
float frameXToYScale = cropRect.Height / cropRect.Width;
float imageXToYScale = image.Size.Height / image.Size.Width;
float scaleFactor;
// Decide if X or Y should be scaled
if (imageXToYScale > frameXToYScale)
{
// Match X dimension of frame
scaleFactor = 1 / (image.Size.Width / cropRect.Size.Width);
}
else
{
// Match Y dimension of frame
scaleFactor = 1 / (image.Size.Height / cropRect.Size.Height);
}
var newImageRect = new RectangleF(0, 0, image.Size.Width * scaleFactor, image.Size.Height * scaleFactor);
UIGraphics.BeginImageContextWithOptions(newImageRect.Size, false, 0);
var context = UIGraphics.GetCurrentContext();
// Flip the image to prepare for display
context.TranslateCTM(0.0f, cropRect.Size.Height);
context.ScaleCTM(1.0f, -1.0f);
// Draw the image in an appropriately-scaled rect
context.DrawImage(newImageRect, image.CGImage);
var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return scaledImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment