An easy way to draw a circle using CAShapeLayer

47,902

An easy way to draw a circle is to create a CAShapeLayer and add a UIBezierPath.

CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)] CGPath]];

let circleLayer = CAShapeLayer();
circleLayer.path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100)).cgPath;

After creating the CAShapeLayer we set its path to be a UIBezierPath.

Our UIBezierPath then draws a bezierPathWithOvalInRect. The CGRect we set will effect its size and position.

Now that we have our circle, we can add it to our UIView as a sublayer.

[[self.view layer] addSublayer:circleLayer];

view.layer.addSublayer(circleLayer)

Our circle is now visible in our UIView.

Circle

If we wish to customise our circle's color properties we can easily do so by setting the CAShapeLayer's stroke- and fill color.

[circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];

shapeLayer.strokeColor = UIColor.red.cgColor;
shapeLayer.fillColor = UIColor.clear.cgColor;

Circle_wColors

Additionall properties can be found over at 's documentation on the subject https://developer.apple.com/.../CAShapeLayer_class/index.html.

Share:
47,902
Aleksander Azizi
Author by

Aleksander Azizi

Developer, security researcher, student. Languages I know offhand: Objective-C SSJS - Node "HTML5" "CSS" CSJS Languages I can navigate with ease: Swift C++ PHP Languages I can work with: Go C C# "Bash" Languages I keep away from: Ruby Perl Java Pyhton "SQL" *quotes for languages that aren't really programming languages.

Updated on May 11, 2020

Comments