Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An easy way to draw a circle using CAShapeLayer

In questions like How to draw a smooth circle..., ...Draw Circle... and ...draw filled Circles the question and answer is very broad, contains lots of unnecessary steps and the methods used isn't always the easiest to re-create or manage.

What is an easy way to draw a circle and add it to my UIView?

like image 968
Aleksander Azizi Avatar asked Feb 10 '15 21:02

Aleksander Azizi


People also ask

How do you draw a circle in iOS Swift?

Enter Swift as Language and choose Storyboard as User Interface, Choose Next. Select File -> New File -> iOS -> Cocoa Touch Class. Name the class CircleView with a subclass of UIView. This class will contain the views where the circles will be drawn.

What is CAShapeLayer in Swift?

Swift version: 5.6. There are lots of CALayer subclasses out there, but CAShapeLayer is one of my favorites: it provides hardware-accelerated drawing of all sorts of 2D shapes, and includes extra functionality such as fill and stroke colors, line caps, patterns and more.


1 Answers

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

objective-c

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

swift

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.

objective-c

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

swift

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.

objective-c

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

swift

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.

like image 178
Aleksander Azizi Avatar answered Oct 19 '22 04:10

Aleksander Azizi