3

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:

enter image description here

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:

enter image description here

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
SagittariusA
  • 5,289
  • 15
  • 73
  • 127
  • 1
    Obviously, it **is** possible, because you managed to draw that white circles without corners :) I think you can solve this problem by yourself. – kelin Dec 16 '15 at 08:53

1 Answers1

2

You need a clipping path, have a look at CGContextClip

Pieter
  • 17,435
  • 8
  • 50
  • 89