这是基于先前评论的版本,该版本首先缩放图像,然后裁剪以按比例填充。
func imageScaledToFillSize(size: CGSize, image: UIImage) -> UIImage
{
let aspect = image.size.width / image.size.height;
UIGraphicsBeginImageContextWithOptions(size, false, 0)
if (size.width / aspect <= size.height) {
let resizedImg = self.imageScaledToSize(CGSize(width: size.height * aspect, height: size.height), image: image)
resizedImg.drawInRect(CGRectMake((size.width - resizedImg.size.width)/2, 0, resizedImg.size.width, resizedImg.size.height))
} else {
let resizedImg = self.imageScaledToSize(CGSize(width: size.width, height: size.width / aspect), image: image)
resizedImg.drawInRect(CGRectMake(0, (size.height-resizedImg.size.height)/2, resizedImg.size.width, resizedImg.size.height))
}
let imageR = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageR;
}
func imageScaledToSize(size: CGSize, image: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
image.drawInRect(CGRectMake(0.0, 0.0, size.width, size.height))
let imageR = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return imageR;
}