In my app I need to have a UIView
whose form is initially a circle but then it can be altered into an ellipse by changing its height or width. So, I have overridden the drawRect()
method like the following:
override func drawRect(rect: CGRect) {
if (self.isRound) {
let ctx:CGContext = UIGraphicsGetCurrentContext()!
CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0)
CGContextSetLineWidth(ctx, 0.5)
CGContextAddEllipseInRect(ctx, rect)
CGContextStrokePath(ctx)
self.layer.cornerRadius = frame.size.width / 2
}
}
which works quite well, returning this result:
I would like to know how to hide, if possibile, those 4 corners so that only the ellipse itself is strictly visibile. Is there a way?
UPDATE and SOLUTION
This is the solution I have found, looking here in all Apple Core Graphics functions concerning ellipses. First of all, if my UIView
is supposed to be an ellipse, in its constructor I take the following trick concerning alpha parameter:
if (self.isRound) {
self.backgroundColor = UIColor(red: 0.0, green: 0.6, blue: 1.0, alpha: 0.0)
}
else {
self.backgroundColor = UIColor(red: 0.0, green: 0.6, blue: 1.0, alpha: 0.4)
}
In this way the background rectangle is not showed at all. Then, this is my drawRect()
method:
override func drawRect(rect: CGRect) {
if (self.isRound) {
let ctx:CGContext = UIGraphicsGetCurrentContext()!
CGContextSetRGBFillColor(ctx, 0.0, 0.6, 1.0, 0.4) /*!!!*/
CGContextFillEllipseInRect(ctx, rect) /*use Fill and not Stroke */
CGContextStrokePath(ctx)
}
}
which gives me this result: