UIImage方面填充

时间:2017-11-18 19:25:39

标签: ios swift uiimage core-graphics

我正在尝试在UIImage上执行方面填充(具有可重复使用的扩展名),但我只有这么远:

extension UIImage {
    func resizeToCircleImage(targetSize: CGSize, contentMode: UIViewContentMode) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(targetSize, true, 0.0)
        let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

所以,这是一个MKAnnotationView。

最终看起来像这样:

enter image description here

但我希望能够适应这种形象:

https://en.wikipedia.org/wiki/Panorama#/media/File:Panorama_of_the_courtyard_of_the_Great_Mosque_of_Kairouan.jpg

1 个答案:

答案 0 :(得分:1)

考虑一类UIImage,

- (UIImage *)aspectFillToSize:(CGSize)size
{
    CGFloat imgAspect = self.size.width / self.size.height;
    CGFloat sizeAspect = size.width/size.height;

    CGSize scaledSize;

        if (sizeAspect > imgAspect) { // increase width, crop height
            scaledSize = CGSizeMake(size.width, size.width / imgAspect);
        } else { // increase height, crop width
            scaledSize = CGSizeMake(size.height * imgAspect, size.height);
        }
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}