简体   繁体   中英

How to draw a circular UIImage on Core Graphics

Inside custom UIView , I've overridden draw() function. I need to draw an image in a circular layout. Also, if possible, I need to resize the image keeping the aspect fill/fit property. How to do that?

Code:

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

This above lines can be used for drawing image. cornerRadius / masksToBounds are not working.

Thanks in advance!

2nd Attempt :

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

Please try this

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

Finally I got the clue,

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)

This is an IBDesignable, have you looked at your clipsToBounds property in the storyboard for the ScoreGraphView?

Try adding this to your class ScoreGraphView as well:

override func awakeFromNib() {
    super.awakeFromNib()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM