IOS: create a UIImage or UIImageView with rounded corners

后端 未结 12 745
执笔经年
执笔经年 2020-12-07 07:26

Is it possible create an UIImage or an UIImageView with rounded corners? Because I want take an UIImage and show it inside an UI

12条回答
  •  春和景丽
    2020-12-07 07:58

    Setting cornerRadius and clipsToBounds is the right way to do this. However if the view's size changes, the radius will not update. In order to get proper resizing and animation behavior, you need to create a UIImageView subclass.

    class RoundImageView: UIImageView {
        override var bounds: CGRect {
            get {
                return super.bounds
            }
            set {
                super.bounds = newValue
                setNeedsLayout()
            }
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            layer.cornerRadius = bounds.width / 2.0
            clipsToBounds = true
        }
    }
    

提交回复
热议问题