ios - UIImage 长宽比填充

标签 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

最佳答案

考虑 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;
}

关于ios - UIImage 长宽比填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47370110/

相关文章:

swift - 更新数组中的对象

ios - 如何在 iOS 中调整图像大小?

swift - iOS 11 : [ImageManager] Unable to load image data

swift - 如何从子 UICollectionview 中获取 UITableView 的一部分

ios - 如何根据文本字段中的用户输入过滤字典数据数组

iphone - 如何获取 UIImage 并给它一个黑色边框?

ios - 禁用 UITableView 离屏渲染

ios - 使用 CocoaPods 添加 GeoFire 依赖项

ios - 使用 UINavigationController View

ios - 在uitableview中将 subview 发送回后,如何触摸 subview ?