iOS: Rounded rectangle with border bleeds color

后端 未结 7 1306
悲&欢浪女
悲&欢浪女 2020-12-09 10:12

I\'m drawing round avatar pics, by just applying cornerRadius to a UIImageView\'s layer, and also adding a border via borderWith and <

相关标签:
7条回答
  • 2020-12-09 10:41

    Here's a subclass of UIImageView that solves this problem.

    As the accepted answer suggests, it adds a rounded CAShapeLayer that has a border width and a corner radius 1px larger than "wanted". Its frame starts at CGPoint(x: 1, y: 1) and has a height 2px larger than the height of the image view. That way, it covers the bleed-through.

    Swift 3+ solution

    Subclass:

    class BorderedRoundedImageView: UIImageView {
        let borderLayer = CALayer()
        
        var borderWidth: CGFloat!
        var borderColor: UIColor!
        
        func setUp() {
            borderLayer.borderWidth = borderWidth + 1
            borderLayer.borderColor = borderColor.cgColor
            layer.addSublayer(borderLayer)
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            borderLayer.cornerRadius = layer.cornerRadius + 1
            borderLayer.frame = CGRect(x: -1, y: -1, width: frame.width + 2, height: frame.height + 2)
        }
    }
    

    Usage:

    @IBOutlet weak var imageView: UIImageView!
    
    [...]
    
    imageView.layer.cornerRadius = 20
    imageView.borderWidth = 2
    imageView.borderColor = .lightGray
    imageView.setUp()
    

    Result:

    0 讨论(0)
提交回复
热议问题