繁体   English   中英

使用drawInRect调整图像大小,同时保持像Scale Aspect Fill一样的宽高比?

[英]Resize an image with drawInRect while maintaining the aspect ratio like Scale Aspect Fill?

我想用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
}

好的,所以没有现成的答案......我为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))

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];

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM