I have a class that makes a UIView of a circle. I when I add the circle to my view, it shows the red outline, but the interior is clear instead of black. I want it to have a black fill.
class CircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setLineWidth(1.0);
UIColor.red.set()
let center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
let radius = (frame.size.width - 10)/2
context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)
context.strokePath()
context.closePath()
context.setFillColor(UIColor.black.cgColor)
context.fillPath()
}
}
}
If you look to the documentation of strokePath():
The current path is cleared as a side effect of calling this function.
Basically, after stroking your path, your paths is reset and there is nothing to fill.
A workaround could be to save context.path
first and then use context.addPath(path)
. However, I usually prefer to build a separate CGMutablePath
first and then add it to the context.