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

How to set corner Radius to UIImage not UIImageView in iOS Swift

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

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

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

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

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

实际图像

给予aspectFit模式时的Image

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

提前致谢...!

您可以尝试 AspectFill 模式,而不是 AspectFit。 使用AspectFill,图像将完全填充imageView,并且会有圆角。

这里是 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)

与 Anton 的回答类似,但有一点不同:

将 UIImageView 放在一个通用的 UIView 中,它充当一个容器,您可以控制其角半径。

示例:

let containerView = UIView()
containerView.layer.cornerRadius = 15
containerView.layer.masksToBounds = true //maybe not necessary
//set some width and height in a CGRect()

let imageView = UIImageView()
containerView.addSubview(imageView)
imageView.frame = containerView.bounds
imageView.contentMode = .scaleAspectFill