OGeek|极客世界-中国程序员成长平台

标题: ios - 如何以编程方式调整 UIImage 的大小以设置 scaleAspectFill 内容模式? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:27
标题: ios - 如何以编程方式调整 UIImage 的大小以设置 scaleAspectFill 内容模式?

我找到了几个例子来调整图像的大小,在给定特定 CGRect 的情况下保持其纵横比,或者例如只有 this post 中的宽度.但是这些示例总是会创建一个看起来像 scaleAspectFit 内容模式的新图像。我想在 scaleAspectFill 内容模式下获得类似的内容,但我没有找到任何示例。



Best Answer-推荐答案


我已将它用于我的一个项目。

extension UIImage
{
    func imageWithSize(size:CGSize) -> UIImage
    {
        var scaledImageRect = CGRect.zero

        let aspectWidth:CGFloat = size.width / self.size.width
        let aspectHeight:CGFloat = size.height / self.size.height

        //max - scaleAspectFill | min - scaleAspectFit
        let aspectRatio:CGFloat = max(aspectWidth, aspectHeight)

        scaledImageRect.size.width = self.size.width * aspectRatio
        scaledImageRect.size.height = self.size.height * aspectRatio
        scaledImageRect.origin.x = (size.width - scaledImageRect.size.width) / 2.0
        scaledImageRect.origin.y = (size.height - scaledImageRect.size.height) / 2.0

        UIGraphicsBeginImageContextWithOptions(size, false, 0)

        self.draw(in: scaledImageRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage!
    }
}

关于ios - 如何以编程方式调整 UIImage 的大小以设置 scaleAspectFill 内容模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44177720/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4