I apply cornerRadius
for UIView
, and apply the border color.
But, I can see the wrong color at the corner.
This image below is an enlarged image for simulator.
And this image below is debug view hierarchy.
How is fix that?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
let test = UIView()
test.backgroundColor = .white
test.layer.cornerRadius = 7
test.layer.borderColor = UIColor.black.cgColor
test.layer.borderWidth = 2
view.addSubview(test)
test.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
test.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 15),
test.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
test.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
test.heightAnchor.constraint(equalToConstant: 40)
])
}
}
2
Answers
I hope I’m correct with your remark, that the border color is not right, because you still see the edges of the background color white on the outer edges of your view.
If that’s the case, you can easily get rid of that with setting your view to clipsToBounds is true. your code then looks only slightly different.
This should solve your problem with the edges.
OK – what you’re seeing is "artifacts" of anti-aliasing of the border… because the border is draw on the inside of the view.
It’s been this way since (I believe) the first version of iOS.
The artifacts are even more noticeable when using a corner radius to make the view round:
and zoomed-in to 200%:
The way to avoid this is to use a
CAShapeLayer
with a rounded-cornerUIBezierPath
.Here’s a quick example view subclass, with public properties similar to what you’re already using on the
.layer
:That gives us:
and, again zoomed-in to 200%:
Here’s an example view controller showing the differences: