【问题标题】:How to set corner Radius to UIImage not UIImageView in iOS Swift如何在 iOS Swift 中将角半径设置为 UIImage 而不是 UIImageView
【发布时间】:2016-12-03 23:13:35
【问题描述】:

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

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

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

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

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

实物图

给予 aspectFit 模式时的图像

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

在此先感谢...!

【问题讨论】:

  • UIIMageVIew 的背景色你设置了吗?
  • 是的,但它是为了向您突出显示图像视图。 (用于发布)
  • 好的,如果对您有帮助,请参考此链接stackoverflow.com/questions/10563986/…
  • 试过了。同样的问题仍然存在。
  • 我仍然没有为这个问题找到正确的解决方案..!在这种情况下谁能帮助我....?

标签: ios swift image uiimageview cornerradius


【解决方案1】:

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

【讨论】:

  • 只有代码的答案不是答案;请提供解释(并正确格式化)。
  • 感谢它运行良好,为您的努力点赞..!
  • 第 4 行的大小是多少?!
  • size 是 UIImage 的一个属性(self.size,其中 self 是 UIImage)。它是可用的,因为我们在 UIImage 的扩展内部。
【解决方案2】:

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

【讨论】:

  • 是的,我试过了。但是有了这个,图像被裁剪了。 (未显示完整图像)
  • 在这种情况下,如果需要显示完整的图像,而不是切割任何小块,您应该在情节提要中为您的 imageView 设置适当的约束。检查图像的纵横比(例如在 Photoshop 中),并将 imageView 的约束“纵横比”设置为相同的值。
  • 我试过了。同样的问题仍然存在。
【解决方案3】:

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

将 UIImageView 放置在通用 UIView 中,该 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多