如何在Core Graphics上绘制圆形UIImage

时间:2017-01-09 10:44:56

标签: ios swift uiimage core-graphics uibezierpath

在自定义UIView内,我已覆盖draw()功能。我需要以圆形布局绘制图像。此外,如果可能,我需要调整图像大小,保持 aspect 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无效。

提前致谢!

4 个答案:

答案 0 :(得分:1)

第二次尝试:

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))
}

答案 1 :(得分:0)

请试试这个

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

答案 2 :(得分:0)

最后我得到了线索,

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)

答案 3 :(得分:-1)

这是一个IBDesignable,您是否在ScoreGraphView的故事板中查看了clipsToBounds属性?

尝试将此添加到您的ScoreGraphView类中:

override func awakeFromNib() {
    super.awakeFromNib()

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