How do I make an UIImage/-View with rounded corners CGRect (Swift)

前端 未结 8 2530
你的背包
你的背包 2020-12-13 01:47

How do I make a UIImageView with rounded corners on a Swift iOS Playground?
Inside it needs to be filled with a color.

8条回答
  •  孤街浪徒
    2020-12-13 02:23

    If you want to have an option to round each UIImageView, you can copy this code into your project without forgetting to check clip to bounds and set its value to true

    import UIKit
    
    @IBDesignable
    extension UIImageView
    {
        private struct AssociatedKey
        {
            static var rounded = "UIImageView.rounded"
        }
    
        @IBInspectable var rounded: Bool
        {
            get
            {
                if let rounded = objc_getAssociatedObject(self, &AssociatedKey.rounded) as? Bool
                {
                    return rounded
                }
                else
                {
                    return false
                }
            }
            set
            {
                objc_setAssociatedObject(self, &AssociatedKey.rounded, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                layer.cornerRadius = CGFloat(newValue ? 1.0 : 0.0)*min(bounds.width, bounds.height)/2
            }
        }
    }
    

    screenshot

提交回复
热议问题