Anda dapat mencapai ini dengan mengatur mode konten tampilan gambar ke UIViewContentModeScaleAspectFill.
Kemudian gunakan metode metode berikut untuk mendapatkan objek uiimage yang diubah ukurannya.
- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
CGFloat width = imageToResize.size.width;
CGFloat height = imageToResize.size.height;
float scaleFactor;
if(width > height)
{
scaleFactor = imageView.frame.size.height / height;
}
else
{
scaleFactor = imageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
[imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
Diedit Di Sini (Versi Swift)
func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
let width = imageToResize.size.width
let height = imageToResize.size.height
var scaleFactor: CGFloat
if(width > height)
{
scaleFactor = onImageView.frame.size.height / height;
}
else
{
scaleFactor = onImageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage;
}