我想用drawInRect方法调整图像大小,但我还想保持正确的宽高比,同时完全填充给定的帧(如.ScaleAspectFill对UIViewContentMode所做的那样)。 任何人都有这方面的答案吗?
这是我的代码(非常简单......):
func scaled100Image() -> UIImage {
let newSize = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(newSize)
self.pictures[0].drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
答案 0 :(得分:24)
好的,所以没有现成的答案......我为UIImage写了一个快速扩展,如果你需要,可以随意使用它。
这是:
extension UIImage {
func drawInRectAspectFill(rect: CGRect) {
let targetSize = rect.size
if targetSize == CGSizeZero {
return self.drawInRect(rect)
}
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
let scalingFactor = max(widthRatio, heightRatio)
let newSize = CGSize(width: self.size.width * scalingFactor,
height: self.size.height * scalingFactor)
UIGraphicsBeginImageContext(targetSize)
let origin = CGPoint(x: (targetSize.width - newSize.width) / 2,
y: (targetSize.height - newSize.height) / 2)
self.drawInRect(CGRect(origin: origin, size: newSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
scaledImage.drawInRect(rect)
}
}
所以在上面的例子中,你可以这样使用它:
self.pictures[0].drawInRectAspectFill(CGRect(x: 0, y: 0, width: 100, height: 100))
答案 1 :(得分:1)
Objective-C版本,如果有人需要它(将此代码粘贴到UIIMage类别中):
- (void) drawInRectAspectFill:(CGRect) recto {
CGSize targetSize = recto.size;
if (targetSize.width <= CGSizeZero.width && targetSize.height <= CGSizeZero.height ) {
return [self drawInRect:recto];
}
float widthRatio = targetSize.width / self.size.width;
float heightRatio = targetSize.height / self.size.height;
float scalingFactor = fmax(widthRatio, heightRatio);
CGSize newSize = CGSizeMake(self.size.width * scalingFactor, self.size.height * scalingFactor);
UIGraphicsBeginImageContext(targetSize);
CGPoint origin = CGPointMake((targetSize.width-newSize.width)/2,(targetSize.height - newSize.height) / 2);
[self drawInRect:CGRectMake(origin.x, origin.y, newSize.width, newSize.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[scaledImage drawInRect:recto];
}