How do I draw a circle in iOS Swift?

swift 5 draw circle
uiview circle swift
uibezierpath circle swift 4
ios draw circle
swift draw circle uiimage
draw circle in swift 4
swift ui circle
swift cgpath circle
let block = UIView(frame: CGRectMake(cellWidth-25, cellHeight/2-8, 16, 16))
block.backgroundColor = UIColor(netHex: 0xff3b30)
block.layer.cornerRadius = 9
block.clipsToBounds = true

This is what I have right now, but it's obviously not the right way to do it.

What's the simplest way to do it?

WARNING! This is incorrect solution - layers are added infinitely in draw method (every time the view is drawn). You should never add layers in draw method. Use layoutSubview instead

You can draw a circle with this:

Swift 2.2:

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    //you can change the line width
    shapeLayer.lineWidth = 3.0

    view.layer.addSublayer(shapeLayer)

Swift 3.0:

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100, y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.cgPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.red.cgColor
    //you can change the line width
    shapeLayer.lineWidth = 3.0

    view.layer.addSublayer(shapeLayer)

With the code you have posted you are cropping the corners of the UIView, not adding a circle to the view.


Here's a full example of using that method:

// make the UIView a ring of color
import UIKit
class Ring:UIView
    {
    override func drawRect(rect: CGRect)
        {
        drawRingFittingInsideView()
        }

    internal func drawRingFittingInsideView()->()
        {
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = 1    // your desired value

        let circlePath = UIBezierPath(
            arcCenter: CGPoint(x:halfSize,y:halfSize),
            radius: CGFloat( halfSize - (desiredLineWidth/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(M_PI * 2),
            clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.CGPath

        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = UIColor.redColor().CGColor
        shapeLayer.lineWidth = desiredLineWidth

        layer.addSublayer(shapeLayer)
        }
    }


Note however there's an incredibly handy call

let circlePath = UIBezierPath(ovalInRect: rect)

which does all the work of making the path. (Don't forget to inset it for the line thickness, which is also incredibly easy with CGRectInset.)

internal func drawRingFittingInsideView(rect: CGRect)->()
    {
    let desiredLineWidth:CGFloat = 4    // your desired value
    let hw:CGFloat = desiredLineWidth/2

    let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw) )

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    shapeLayer.lineWidth = desiredLineWidth
    layer.addSublayer(shapeLayer)
    }


In practice these days in Swift, you would certainly use

@IBDesignable

and

@IBInspectable

In this way you can actually see and change the rendering, in Storyboard!

As you can see, it actually adds new features to the Inspector on the Storyboard, which you can change on the Storyboard:

Here's the code...

// Dot with border, which you can control completely in Storyboard
import UIKit
@IBDesignable
class Dot:UIView
    {
    @IBInspectable var mainColor: UIColor = UIColor.blueColor()
        {
        didSet { print("mainColor was set here") }
        }
    @IBInspectable var ringColor: UIColor = UIColor.orangeColor()
        {
        didSet { print("bColor was set here") }
        }
    @IBInspectable var ringThickness: CGFloat = 4
        {
        didSet { print("ringThickness was set here") }
        }

    @IBInspectable var isSelected: Bool = true

    override func drawRect(rect: CGRect)
        {
        let dotPath = UIBezierPath(ovalInRect:rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.CGPath
        shapeLayer.fillColor = mainColor.CGColor
        layer.addSublayer(shapeLayer)

        if (isSelected) { drawRingFittingInsideView(rect) }
        }

    internal func drawRingFittingInsideView(rect: CGRect)->()
        {
        let hw:CGFloat = ringThickness/2
        let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw) )

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.CGPath
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = ringColor.CGColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
        }
    }

Finally, note that if you have a UIView (which is square, and which you set to say red in Storyboard) and you simply want to turn it in to a red circle, you can just do the following:

// It makes a UIView into a circular dot of color
import UIKit
class Dot:UIView
    {
    override func layoutSubviews()
        { layer.cornerRadius = bounds.size.width/2; }
    }

Draw Circles iOS Tutorial, Enter Swift as Language and choose Storyboard as User Interface, Choose Next. View fullsize. ios-draw-circles  Questions: let block = UIView(frame: CGRectMake(cellWidth-25, cellHeight/2-8, 16, 16)) block.backgroundColor = UIColor(netHex: 0xff3b30) block.layer.cornerRadius = 9 block.clipsToBounds = true This is what I have right now, but it’s obviously not the right way to do it.

If you want to use a UIView to draw it, then you need to make the radius / of the height or width.

so just change:

block.layer.cornerRadius = 9

to:

block.layer.cornerRadius = block.frame.width / 2

You'll need to make the height and width the same however. If you'd like to use coregraphics, then you'll want to do something like this:

CGContextRef ctx= UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];

CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
CGContextSaveGState(ctx);

CGContextSetLineWidth(ctx,5);
CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0);
CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);

How to draw a circle using Core Graphics: addEllipse(in:), Now we need to insert our “pie chart” drawing code in between these two UIBezierPaths we have created. Also, setting the “fill” is filling the path with that color. If  For the Love of Physics - Walter Lewin - May 16, 2011 - Duration: 1:01:26. Lectures by Walter Lewin. They will make you ♥ Physics. Recommended for you

Make a class UIView and assign it this code for a simple circle

import UIKit
@IBDesignable
class DRAW: UIView {

    override func draw(_ rect: CGRect) {

        var path = UIBezierPath()
        path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100))
        UIColor.yellow.setStroke()
        UIColor.red.setFill()
        path.lineWidth = 5
        path.stroke()
        path.fill()


    }


}

Lets create a Custom UIView Circle Indicator in Swift, Circle. A circle centered on the frame of the view containing it. SDKs. iOS 13.0+; macOS 10.15+; Mac Catalyst 13.0+; tvOS 13.0+; watchOS Creating a Circle. In my game, I want to have a circle of dot objects. I have looked up everything but I cannot seem to figure it out. What I wanted was a circle of dots each that was an individual node that I could use to be able to add animations to each individual node. Is there a way to draw multiple shapes in a circular pattern like this?

Updating @Dario's code approach for Xcode 8.2.2, Swift 3.x. Noting that in storyboard, set the Background color to "clear" to avoid a black background in the square UIView:

import UIKit
@IBDesignable
class Dot:UIView
{
    @IBInspectable var mainColor: UIColor = UIColor.clear
        {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = UIColor.clear
        {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4
        {
        didSet { print("ringThickness was set here") }
    }


    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect)
    {

        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) { drawRingFittingInsideView(rect: rect) }
    }

    internal func drawRingFittingInsideView(rect: CGRect)->()
    {
        let hw:CGFloat = ringThickness/2
        let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw,dy: hw) )

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

And if you want to control the start and end angles:

import UIKit
@IBDesignable
class Dot:UIView
{
    @IBInspectable var mainColor: UIColor = UIColor.clear
        {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = UIColor.clear
        {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4
        {
        didSet { print("ringThickness was set here") }
    }


    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect)
    {

        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) { drawRingFittingInsideView(rect: rect) }
    }

    internal func drawRingFittingInsideView(rect: CGRect)->()
    {
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = ringThickness   // your desired value

        let circlePath = UIBezierPath(
            arcCenter: CGPoint(x: halfSize, y: halfSize),
            radius: CGFloat( halfSize - (desiredLineWidth/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(Double.pi),
            clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

Swift Fun Algorithms: How to Draw a Circle using Math, iOS 3.2+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+ radius. Specifies the radius of the circle used to define the arc. The direction in which to draw the arc​. In XCode 7.3.1, with Swift version 2.2, the simplest way to draw a line is to create a playground and insert this code in it. Hope this helps other people with this simple task in mind.

Swift 4 version of accepted answer:

@IBDesignable
class CircledDotView: UIView {

    @IBInspectable var mainColor: UIColor = .white {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = .black {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4 {
        didSet { print("ringThickness was set here") }
    }

    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect) {
        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) {
            drawRingFittingInsideView(rect: rect)
        }
    }

    internal func drawRingFittingInsideView(rect: CGRect) {
        let hw: CGFloat = ringThickness / 2
        let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw, dy: hw))

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

Circle, To subclass the UIView class which you want to draw the custom shape to, and use its Now open the ViewController.swift file, and add the following method: An interesting case is how we turn an oval shape into a circle. Swift 3 - custom class, easy to reuse. Swift 3 class: Another way of approaching circle (and other shapes) drawing is by using masks. You draw circles or other shapes by, first, making masks of the shapes you need, second, provide squares of your color and, third, apply masks to those squares of color.

bezierPathWithArcCenter:radius:startAngle , Update note: This tutorial has been updated to iOS 11, Swift 4, and Xcode 9 by Andrew Drawing in the context is based on this unit circle. I try to make a 20x20 UIImage with a simple blue circle. I try with this function, but the result is a blue circle in a black square. How do I remove the black square around the circle? Function:

A Beginner's Guide to Bezier Paths and Shape Layers, The following code will draw a thin, non-animated circular border around a view. (See below for drawing animated circles.) Update: Thanks to @  I need to be able to programmatically draw on an image, and save that image for later use. Say, draw a line on specific x and y coordinates on the image, save the image, and display it onto a simple view controller. How would I go about doing this in Swift? (Preferably Swift 2, I am still in development and haven't updated my mac to Sierra)

Core Graphics Tutorial Part 1: Getting Started, How to draw a circle using Core Graphics: addEllipse(in:) Swift version: 5.0. Paul Hudson @twostraws May 28th 2019. Core Graphics is able to draw circles and ellipses with just a few lines of code, although there is some set up to do first. The example code below creates a 512x512 circle with a red fill and a black border:

Comments
  • You have a number of ways you can do this, SpriteKit, Core Graphics, etc. You should probably nail it down a little more for us.
  • Cannot see the slightest reason, at all, anyone would vote to close this question?
  • @Joe I'm pretty sure you can earn points as an administrator for certain activities, including closing questions. That probably explains why five people are cited as closing the question when (for four of them) it was already closed.
  • Hi Vince - right, I don't get it. It is totally bizarre this question was closed. Also it is marked "unclear". It just couldn't be more clear, it is crystal clear. Bizarre!
  • Questions about improving working code are better asked on code review.
  • Thanks for the answer! Do you know the perf difference between using cornerRadius and BezierPath? Just curious :)
  • M_PI is deprecated. It's now Double.pi (in Swift 3)
  • It is probably not good idea to add new CALayer in func drawRect(rect: CGRect) method, as this method is supposed to do custom drawing in its own layer, also this method would be called mulitple times.
  • Please, DO NOT ADD sublayers in drawRect method! First, drawRect is called multiple times during view lifecycle, literally every layout process. That means, you will end up having dozens of equal (or probably not) sublayers in your hierarchy, consuming memory and slowing your app down. Second, drawRect isn't intended for modifying view hierarchy. If you really need to draw something special - you use it in conjunction with CoreGraphics context functions. Better way here - is just adding shape layer in init method.
  • Very clever. Making a circle by using a square. Made it really easy for me.
  • This is the only correct answer to the date, others have major issue.
  • Thanks for the Swift 3 translations, saved me a lot of time and testing!
  • WARNING! This is incorrect solution - layers are added infinitely in draw method (every time the view is drawn).
  • @AlexanderVolkov good catch. I’m away from my iOS dev station for a few weeks, do you have a fix or improvement?