I\'m drawing round avatar pics, by just applying cornerRadius
to a UIImageView
\'s layer, and also adding a border via borderWith
and <
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.
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: