ios - 如何在 iOS Swift 中将角半径设置为 UIImage 而不是 UIImageView

标签 ios swift image uiimageview cornerradius

谁能帮帮我……!我只想为图像设置角半径,而且图像必须适合 AspectFit 比例。

如果我提供 scaleToFill 模式,我可以使用下面的代码并且它工作正常。但图像已被拉伸(stretch)。

self.productImg.layer.cornerRadius = 7
self.productImg.clipsToBounds = true

但是当将比例赋予 AspectFit 时,它显示如下图所示。

显示的绿色是 ImageView ,其中图像设置为 aspectFit。

实际图像

Actual image

给予aspectFit模式时的Image

Image when giving the aspectFit mode

我需要实际给出的图像,并且它必须具有圆角半径。所以请任何人给我解决这个问题的解决方案。

提前致谢...!

最佳答案

这里是 UIImage 的一个扩展,用于为其设置圆角半径,而不是处理 UIImageView。

 extension UIImage {
        // image with rounded corners
        public func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
            let maxRadius = min(size.width, size.height) / 2
            let cornerRadius: CGFloat
            if let radius = radius, radius > 0 && radius <= maxRadius {
                cornerRadius = radius
            } else {
                cornerRadius = maxRadius
            }
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            let rect = CGRect(origin: .zero, size: size)
            UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
            draw(in: rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }

用法:

yourUIImage.withRoundedCorners(radius: 10)

关于ios - 如何在 iOS Swift 中将角半径设置为 UIImage 而不是 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38655374/

相关文章:

ios - 用于具有动态高度的 View /标签的 Swift heightForRowAtIndexPath

ios - AFNetworking 中 "setImageWithURLRequest: placeholderImage: success:"的 Alamofire 方式

Android,如何实例化Universal Image Loader?

linux - 转换-追加*网格

悬停时带有 Logo 的 CSS 背景图片

ios - nsuserdefault 有key-values set 如何删除呢?

ios - 从字典中删除整个元素

arrays - 无法创建 SKActions 数组

ios - 从 swift 向 NSMutableArray 添加字典

ios - 即使将重复间隔设置为工作日,UILocalNotification 也会每天触发