如何在 Core Graphics 上绘制圆形 UIImage

How to draw a circular UIImage on Core Graphics

在自定义 UIView 中,我覆盖了 draw() 函数。我需要以圆形布局绘制图像。另外,如果可能的话,我需要调整图像大小以保持 纵横比 fill/fit 属性。怎么做?

代码:

@IBDesignable class ScoreGraphView: UIView {

    override func draw(_ rect: CGRect) {

        let iv = UIImageView(image: UIImage(named: "women"))
        iv.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
        iv.layer.cornerRadius = 20
        iv.clipsToBounds = true
        iv.layer.masksToBounds = true
        iv.backgroundColor = UIColor.clear
        iv.draw(CGRect(x: 0, y: 0, width: rect.width, height: rect.height))
    }
}

以上这几行可以用来画图。 cornerRadius/masksToBounds 不工作。

提前致谢!

这是一个 IBDesignable,您是否在 ScoreGraphView 的情节提要中查看了 clipsToBounds 属性?

也尝试将此添加到您的 class ScoreGraphView:

override func awakeFromNib() {
    super.awakeFromNib()

    self.clipsToBounds = true
    self.layer.masksToBounds = true
}

第二次尝试:

override func draw(_ rect: CGRect) {
    layer.cornerRadius = 20
    clipsToBounds = true
    let iv = UIImageView(image: UIImage(named: "women"))
    iv.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
    iv.draw(CGRect(x: 0, y: 0, width: rect.width, height: rect.height))
}

请试试这个

imageView.layer.cornerRadius = imgProfile.frame.size.height/2
imageView.clipsToBounds = true

终于明白了,

let userimageView : UIImageView = UIImageView(frame: rect)
userimageView.image = UIImage(named: "women")
userimageView.backgroundColor = UIColor.clear;
userimageView.alpha = 1.0
userimageView.clipsToBounds = false
userimageView.layer.cornerRadius = 20.0
userimageView.layer.masksToBounds = true

self.layer.addSublayer(userimageView.layer)