How to keep a round imageView round using auto layout?

后端 未结 15 1384
悲&欢浪女
悲&欢浪女 2020-12-01 06:22

How do I turn a rectangular image view into a circular image view that can hold shape in auto layout without setting width and height restraints? Thereby allowing the imageV

15条回答
  •  暖寄归人
    2020-12-01 06:43

    First of all, I should mention that u can get a circle shape for your UIView/UIImageView only if the width and height will be equal. It's important to understand. In all other cases (when width != height), you won't get a circle shape because the initial shape of your UI instance was a rectangle.

    OK, with this so UIKit SDK provides for developers a mechanism to manipulate the UIview's layer instance to change somehow any of layer's parameters, including setting up a mask to replace the initial shape of UIView element with the custom one. Those instruments are IBDesignable/IBInspectable. The goal is to preview our custom views directly through Interface Builder.

    So using those keywords we can write our custom class, which will deal only with the single condition whether we need to round corners for our UI element or not.

    For example, let's create the class extended from the UIImageView.

    @IBDesignable
    class UIRoundedImageView: UIImageView {
    
        @IBInspectable var isRoundedCorners: Bool = false {
            didSet { setNeedsLayout() }
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if isRoundedCorners {
                let shapeLayer = CAShapeLayer()
                shapeLayer.path = UIBezierPath(ovalIn:
                    CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height
                )).cgPath
                layer.mask = shapeLayer
            }
            else {
                layer.mask = nil
            }
    
        }
    
    }
    

    After setting the class name for your UIImageView element (where the dog picture is), in your storyboard, you will get a new option, appeared in the Attributes Inspector menu (details at the screenshot).

    The final result should be like this one.

提交回复
热议问题