iOS (Swift) Annuls-shaped UIBezierPath for CAShapeLayer - ios

I'm trying to make an annulus-shaped UIBezierPath to use as the path of a CAShapeLayer
The following produces a circular path:
let radius = 100.0
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
However, I want an annuls-shaped UIBezierPath that fills between radius and say outerRadius = radius + 10.

If this is what you're going for ("Annulus" shape):
You can achieve it by creating an Oval path and appending a smaller Oval path.
You can run this directly in a Playground page to get that result:
import PlaygroundSupport
import UIKit
class AnnulusView: UIView {
private var annulusLayer: CAShapeLayer!
private var annulusWidth: CGFloat = 10.0
private var fillColor: UIColor = .red
override func layoutSubviews() {
super.layoutSubviews()
if annulusLayer == nil {
annulusLayer = CAShapeLayer()
layer.addSublayer(annulusLayer)
}
let r = bounds
let outerPath = UIBezierPath(ovalIn: r)
let innerPath = UIBezierPath(ovalIn: r.insetBy(dx: annulusWidth, dy:annulusWidth))
outerPath.append(innerPath)
outerPath.usesEvenOddFillRule = true
annulusLayer.path = outerPath.cgPath
annulusLayer.fillRule = kCAFillRuleEvenOdd
annulusLayer.fillColor = fillColor.cgColor
// if you want a border
// annulusLayer.lineWidth = 1
// annulusLayer.strokeColor = UIColor.black.cgColor
}
}
class TestingViewController: UIViewController {
override public var preferredContentSize: CGSize {
get { return CGSize(width: 400, height: 400) }
set { super.preferredContentSize = newValue }
}
var theAnnulusView: AnnulusView = {
let v = AnnulusView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(theAnnulusView)
// make the Annulus view 100x100 centered in this view
NSLayoutConstraint.activate([
theAnnulusView.widthAnchor.constraint(equalToConstant: 100),
theAnnulusView.heightAnchor.constraint(equalToConstant: 100),
theAnnulusView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
theAnnulusView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
let viewController = TestingViewController()
PlaygroundPage.current.liveView = viewController

Check out this, It might be helpful.
If you need a full circle, you need to adjust arcCenter
let width:CGFloat = 10
let radius:CGFloat = 100.0-width/2
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.lineWidth = width
layer.path = circularPath.cgPath

Related

How to draw a circle using CAShapeLayer to be centered in a custom UIView in swift programmatically

I am trying to draw a circular progress bar using CAShapeLayer inside a custom UIView which has been auto constraint, I don't want to draw my circle in the center of my super view but rather in the center of my custom view because I have other views on top my code below draws a circle but it is not positioned in the specified view
// Custom View
let gaugeViewHolder = UIView()
scrollView.addSubview(gaugeViewHolder)
gaugeViewHolder.translatesAutoresizingMaskIntoConstraints = false
gaugeViewHolder.backgroundColor = UIColor.black
gaugeViewHolder.leadingAnchor.constraint(equalTo: motherView.leadingAnchor).isActive = true
gaugeViewHolder.topAnchor.constraint(equalTo: defaultAccImage.bottomAnchor, constant: 70).isActive = true
gaugeViewHolder.trailingAnchor.constraint(equalTo: motherView.trailingAnchor).isActive = true
gaugeViewHolder.heightAnchor.constraint(equalToConstant: 200).isActive = true
//Now my circle
let shapeLayer = CAShapeLayer()
let centerForGauge = gaugeViewHolder.center
let circularPath = UIBezierPath(arcCenter: centerForGauge
, radius: 80, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.white.withAlphaComponent(0.20).cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
gaugeViewHolder.layer.addSublayer(shapeLayer)
let gaugeViewHolder = UIView()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.addSubview(gaugeViewHolder)
gaugeViewHolder.translatesAutoresizingMaskIntoConstraints = false
gaugeViewHolder.backgroundColor = UIColor.black
gaugeViewHolder.leadingAnchor.constraint(equalTo: motherView.leadingAnchor).isActive = true
gaugeViewHolder.topAnchor.constraint(equalTo: defaultAccImage.bottomAnchor, constant: 70).isActive = true
gaugeViewHolder.trailingAnchor.constraint(equalTo: motherView.trailingAnchor).isActive = true
gaugeViewHolder.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let shapeLayer = CAShapeLayer()
let centerForGauge = gaugeViewHolder.center
print("gauge width:: \(centerForGauge)")
let circularPath = UIBezierPath(arcCenter: CGPoint(x: gaugeViewHolder.frame.size.width/2, y: gaugeViewHolder.frame.size.height/2)
, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.white.withAlphaComponent(0.50).cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
gaugeViewHolder.layer.addSublayer(shapeLayer)
}
You may consider add the layer later after all constraints has been applied to your view if you don't set frame by yourself at design time. This works as I have tested in an example.
var gaugeViewHolder : UIView!
override func viewDidLoad() {
super.viewDidLoad()
gaugeViewHolder = UIView()
scrollView.addSubview(gaugeViewHolder)
gaugeViewHolder.translatesAutoresizingMaskIntoConstraints = false
gaugeViewHolder.backgroundColor = UIColor.black
gaugeViewHolder.leadingAnchor.constraint(equalTo: motherView.leadingAnchor).isActive = true
gaugeViewHolder.topAnchor.constraint(equalTo: defaultAccImage.bottomAnchor, constant: 70).isActive = true
gaugeViewHolder.trailingAnchor.constraint(equalTo: motherView.trailingAnchor).isActive = true
gaugeViewHolder.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let shapeLayer = CAShapeLayer()
let centerForGauge = gaugeViewHolder.center
let circularPath = UIBezierPath(arcCenter: centerForGauge
, radius: 80, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.white.withAlphaComponent(0.20).cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = CAShapeLayerLineCap.round
gaugeViewHolder.layer.addSublayer(shapeLayer)
}
You never set the frame of the shape layer. It should be the owning view's bounds rect if you want the shape layer to overlay the view's rectangle.
Here is code that adds a shape layer to a view that I added in a sample app storyboard and wired up as an IBOutlet:
#IBOutlet weak var gaugeViewHolder: UIView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
gaugeViewHolder.backgroundColor = UIColor.lightGray
//Now my circle
let shapeLayer = CAShapeLayer()
shapeLayer.borderWidth = 2.0 //Add a box on the shape layer so you can see where it gets drawn.
shapeLayer.frame = gaugeViewHolder.bounds //Use the view's bounds as the layer's frame
//Convert gaugeViewHolder's center from it's superview's coordinate system to it's coordinate system
let centerForGauge = gaugeViewHolder?.superview?.convert(gaugeViewHolder.center, to: gaugeViewHolder) ?? CGPoint.zero
let lineWidth = CGFloat(5.0)
//Use 1/2 the shortest side of the shapeLayer's frame for the radius, inset for the circle path's thickness.
let radius = max(shapeLayer.frame.size.width, shapeLayer.frame.size.height)/2.0 - lineWidth / 2.0
let circularPath = UIBezierPath(arcCenter: centerForGauge
, radius: radius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.yellow.cgColor
shapeLayer.lineCap = .round
gaugeViewHolder.layer.addSublayer(shapeLayer)
}
I changed the colors and alpha around, and added a borderWidth to the shape layer to make everything stand out.

Circular timer using CAShapelayer

Tried to create a circular timer for my app end up with this
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let progressWidth: CGFloat = 10;
let centerX = CGRectGetMidX(rect)
let centerY = CGRectGetMidY(rect)
let center: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
let radius: CGFloat = rect.width / 2
var circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let backgroundCircle = CAShapeLayer()
backgroundCircle.path = circlePath.CGPath
backgroundCircle.fillColor = backgroundCircleFillColor
self.layer.addSublayer(backgroundCircle)
circlePath = UIBezierPath(arcCenter: center, radius: radius-progressWidth/2, startAngle: -CGFloat(GLKMathDegreesToRadians(90)), endAngle:CGFloat(GLKMathDegreesToRadians(currentAngle)), clockwise: true)
let progressCircle = CAShapeLayer()
progressCircle.path = circlePath.CGPath
progressCircle.lineWidth = progressWidth
progressCircle.strokeColor = progressCircleStrokeColor
progressCircle.fillColor = UIColor.clearColor().CGColor
self.layer.addSublayer(progressCircle)
let innerCirclePath = UIBezierPath(arcCenter: center, radius: radius-progressWidth, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let innerCircle = CAShapeLayer()
innerCircle.path = innerCirclePath.CGPath
innerCircle.fillColor = innerCircleFillColor
self.layer.addSublayer(innerCircle)
}
List item
Here is the output got from my code:
Main problems faced in this code are
Phone is getting heat while drawing the circle
After drawning half of the circle drowning speed decreased
Please help me with an alternative
Try this :
import UIKit
class CircularProgressBar: UIView {
let shapeLayer = CAShapeLayer()
let secondShapeLayer = CAShapeLayer()
var circularPath: UIBezierPath?
override init(frame: CGRect) {
super.init(frame: frame)
print("Frame: \(self.frame)")
makeCircle()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
makeCircle()
}
func makeCircle(){
let circularPath = UIBezierPath(arcCenter: .zero, radius: self.bounds.width / 2, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.orange.cgColor//UIColor.init(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
shapeLayer.lineWidth = 5.0
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
shapeLayer.position = self.center
shapeLayer.transform = CATransform3DRotate(CATransform3DIdentity, -CGFloat.pi / 2, 0, 0, 1)
self.layer.addSublayer(shapeLayer)
}
func showProgress(percent: Float){
shapeLayer.strokeEnd = CGFloat(percent/100)
}
}
Take a UIView in Storyboard and add it as a subView. Then you can increase the progress using showProgress function.
You shouldn't add layers in drawRect:. Every time your view is drawn, you're adding a layer. That's why it's not surprising that your iPhone is suffering from it and is getting slower and hotter. You should create your layers in viewDidLoad or where your view is created, and you shouldn't modify them in drawRect. This method is only for drawing and nothing else.
I did it like this and worked for me. We need two layers, one for circle and another for progress.
private let circularProgressView = UIView()
private let circleLayer = CAShapeLayer()
private let progressLayer = CAShapeLayer()
private var circularPath: UIBezierPath?
private func setupCircularProgressBar() {
circularPath = UIBezierPath(arcCenter: CGPoint(x: circularProgressView.frame.size.width / 2.0,
y: circularProgressView.frame.size.height / 2.0),
radius: circularProgressView.bounds.width / 2, startAngle: -.pi / 2,
endAngle: 3 * .pi / 2, clockwise: true)
circleLayer.path = circularPath?.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineCap = .round
circleLayer.lineWidth = 5
circleLayer.strokeColor = UIColor.darkGray.cgColor
progressLayer.path = circularPath?.cgPath
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .round
progressLayer.lineWidth = 3
progressLayer.strokeEnd = 0
progressLayer.strokeColor = UIColor.white.cgColor
circularProgressView.layer.addSublayer(circleLayer)
circularProgressView.layer.addSublayer(progressLayer)
}
private func animateCircularProgress(duration: TimeInterval) {
let circularProgressAnimation = CABasicAnimation(keyPath: "strokeEnd")
circularProgressAnimation.duration = duration
circularProgressAnimation.toValue = 1
circularProgressAnimation.fillMode = .forwards
circularProgressAnimation.isRemovedOnCompletion = false
progressLayer.add(circularProgressAnimation, forKey: "progressAnim")
}
usage is very simple you only call animateCircularProgress method with time interval parameter like this with 5 sec duration: animateCircularProgress(duration: 5)

Creating a UIView programmatically

If I create a UIView with a frame like - UIView(frame:..) AND also set constraints on this view will the frame dimensions take precedence over the constraints? Will iOS runtime ignore the constraints?
I created a UIView in viewDidLoad() with a frame and attached constraints to this view. However the constraints are not being enforced at all and the view is rendered in the frame passed to the initializer.
[Edit]
My code is below. I am trying to add an overlay to AVCaptureVideoPreviewLayer (viewPreviewLayer) programatically on top of a UIView (previewContainer, configured with constraints on storyboard) that covers the entire screen.
....
var videoPreviewLayer:AVCaptureVideoPreviewLayer!
#IBOutlet weak var previewContainer: UIView!
....
override func viewDidLoad() {
.....
self.configurePreviewLayer()
}
override func viewDidLayoutSubviews() {
print("viewDidLayoutSubviews")
super.viewDidLayoutSubviews()
self.videoPreviewLayer.frame = self.previewContainer.bounds
}
func configurePreviewLayer() {
print("configurePreviewLayer()")
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
self.videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.previewContainer.layer.addSublayer(self.videoPreviewLayer)
configureBlurView()
}
func configureBlurView() {
print("configureBlurView()")
// Blur View
let viewFinderRadius:CGFloat = self.view.bounds.width / 2.0 - 16.0
print("configureBlurView:\(self.previewContainer.bounds.size.height)")
let blurView = createOverlay(frame:self.previewContainer.bounds,xOffset: self.view.bounds.size.width / 2.0, yOffset: self.view.bounds.size.height / 2.0, radius: viewFinderRadius)
blurView.translatesAutoresizingMaskIntoConstraints = false
self.previewContainer.addSubview(blurView)
self.blurView = blurView
blurView.leftAnchor.constraint(equalTo: self.previewContainer.leftAnchor).isActive = true
blurView.topAnchor.constraint(equalTo:self.previewContainer.topAnchor).isActive = true
blurView.rightAnchor.constraint(equalTo:self.previewContainer.rightAnchor).isActive = true
blurView.bottomAnchor.constraint(equalTo:self.previewContainer.bottomAnchor).isActive = true
}
func createOverlay(frame : CGRect, xOffset: CGFloat, yOffset: CGFloat, radius: CGFloat) -> UIView
{
let overlayView = UIView(frame: frame)
overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
let path = CGMutablePath()
path.addArc(center: CGPoint(x: xOffset, y: yOffset), radius: radius, startAngle: 0.0, endAngle: 2.0 * CGFloat.pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size))
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
return overlayView
}
Here is how the rendered screen looks (As you can see the overlay doesn't cover the entire screen or in other words the entire bounds of previewContainer) -
[Update]
I may have found the culprit. It is this piece of code that masks the overlay -
let path = CGMutablePath()
path.addArc(center: CGPoint(x: xOffset, y: yOffset), radius: radius, startAngle: 0.0, endAngle: 2.0 * CGFloat.pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size))
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
overlayView.layer.mask = maskLayer
If I remove the above mask everything is rendered properly. Now I need to figure out how to draw that mask (view finder for the camera).
Will iOS runtime ignore the constraints?
If the constraints are set properly, no: it will ignore the frame. However, you have not shown what you did, so it is impossible to say what you are seeing and why.

Animation in swift : Circular Dashed Loading Bar?

I have literally looked over the web for like 2to3 hours, unfortunately couldn't find anything, (2nd problem: being new to swift ->this can be ignored)
Basically I need Circular dashed Loading bar : Every dot should animate Individually like a circular load..
I was able to make a circular dashed circle but couldn't animate it...
Any help would be appreciated even if thats an library from github or anything..
Here's my code for creating a circular dashed circle..
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius: 100.0, startAngle: 0.0, endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.position = CGPoint(x: 100, y: 100)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 6.0
let one : NSNumber = 1
let two : NSNumber = 13
shapeLayer.lineDashPattern = [one,two]
shapeLayer.lineCap = kCALineCapRound
view.layer.addSublayer(shapeLayer)
}
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()}
}
This is what I want (Below One):
I have been playing around with custom activity indicators, so here's one way to do it
import UIKit
#IBDesignable class ActivityIndicatorCircle: UIView {
var timerInterval: Double = 0.1
var timer : Timer?
var endAngle: CGFloat = 0.0
var angleStep = CGFloat.pi / 20.0
var angleOffset = -CGFloat.pi / 2.0
var shapeLayer = CAShapeLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func startAnimating() {
superview?.bringSubview(toFront: self)
layer.cornerRadius = frame.width / 2
self.clipsToBounds = true
isHidden = false
timer?.invalidate()
timer = nil
timer = Timer.scheduledTimer(timeInterval: timerInterval,
target: self,
selector: #selector(self.updateCircle),
userInfo: nil,
repeats: true)
}
func stopAnimating() {
isHidden = true
timer?.invalidate()
timer = nil
}
func updateCircle() {
endAngle += angleStep
if endAngle > CGFloat.pi * 2.0 {
endAngle -= CGFloat.pi * 2.0
}
DispatchQueue.main.async {
self.shapeLayer.removeFromSuperlayer() // remove the previous version
let lineWidth: CGFloat = 6.0
let radius = self.frame.size.width / 2.0 // if the view is square, this gives us center as well
let circlePath = UIBezierPath(arcCenter: CGPoint(x: radius,y: radius), radius: radius - lineWidth, startAngle: self.angleOffset, endAngle: self.endAngle + self.angleOffset, clockwise: true)
self.shapeLayer.path = circlePath.cgPath
self.shapeLayer.position = CGPoint(x: 0, y: 0)
self.shapeLayer.fillColor = UIColor.clear.cgColor
self.shapeLayer.strokeColor = UIColor.blue.cgColor
self.shapeLayer.lineWidth = lineWidth
let one : NSNumber = 1
let two : NSNumber = 13
self.shapeLayer.lineDashPattern = [one,two]
self.shapeLayer.lineCap = kCALineCapRound
self.layer.addSublayer(self.shapeLayer)
}
}
}
to use this, add a UIView to your storyboard, and set the class to ActivityIndicatorCircle
To start it, call activityIndicatorCircle.startAnimating()
for circular loader you can use this library it will help you. https://github.com/naoyashiga/RPLoadingAnimation

How do I draw a circle in iOS Swift?

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?
Alert. This old answer is absolutely incorrect.
WARNING! This is an incorrect solution. layers are added infinitely in the drawRect method (every time the view is drawn). You should NEVER add layers in the drawRect method. Use layoutSubview instead.
You can draw a circle with this (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:
/// A special UIView displayed as a ring of color
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. Using these 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:
/// A dot with a border, which you can control completely in Storyboard
#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:
// Makes a UIView into a circular dot of color
class Dot: UIView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.width/2
}
}
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()
}
}
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);
Here is my version using Swift 5 and Core Graphics.
I have created a class to draw two circles. The first circle is created using addEllipse(). It puts the ellipse into a square, thus creating a circle. I find it surprising that there is no function addCircle(). The second circle is created using addArc() of 2pi radians
import UIKit
#IBDesignable
class DrawCircles: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
print("could not get graphics context")
return
}
context.setLineWidth(2)
context.setStrokeColor(UIColor.blue.cgColor)
context.addEllipse(in: CGRect(x: 30, y: 30, width: 50.0, height: 50.0))
context.strokePath()
context.setStrokeColor(UIColor.red.cgColor)
context.beginPath() // this prevents a straight line being drawn from the current point to the arc
context.addArc(center: CGPoint(x:100, y: 100), radius: 20, startAngle: 0, endAngle: 2.0*CGFloat.pi, clockwise: false)
context.strokePath()
}
}
in your ViewController's didViewLoad() add the following:
let myView = DrawCircles(frame: CGRect(x: 50, y: 50, width: 300, height: 300))
self.view.addSubview(myView)
When it runs it should look like this. I hope you like my solution!
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)
}
}
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)
}
}
A much easier and resource friendly approach would be.
import UIKit
#IBDesignable
class CircleDrawView: UIView {
#IBInspectable var borderColor: UIColor = UIColor.red;
#IBInspectable var borderSize: CGFloat = 4
override func draw(_ rect: CGRect)
{
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderSize
layer.cornerRadius = self.frame.height/2
}
}
With Border Color and Border Size and the default Background property you can define the appearance of the circle.
Please note, to draw a circle the view's height and width have to be equal in size.
The code is working for Swift >= 4 and Xcode >= 9.
I find Core Graphics to be pretty simple for Swift 3:
if let cgcontext = UIGraphicsGetCurrentContext() {
cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}
A simple function drawing a circle on the middle of your window frame, using a multiplicator percentage
/// CGFloat is a multiplicator from self.view.frame.width
func drawCircle(withMultiplicator coefficient: CGFloat) {
let radius = self.view.frame.width / 2 * coefficient
let circlePath = UIBezierPath(arcCenter: self.view.center, radius: radius, 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
shapeLayer.strokeColor = UIColor.darkGray.cgColor
shapeLayer.lineWidth = 2.0
view.layer.addSublayer(shapeLayer)
}
Add in view did load
//Circle Points
var CircleLayer = CAShapeLayer()
let center = CGPoint (x: myCircleView.frame.size.width / 2, y: myCircleView.frame.size.height / 2)
let circleRadius = myCircleView.frame.size.width / 2
let circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: CGFloat(M_PI), endAngle: CGFloat(M_PI * 4), clockwise: true)
CircleLayer.path = circlePath.cgPath
CircleLayer.strokeColor = UIColor.red.cgColor
CircleLayer.fillColor = UIColor.blue.cgColor
CircleLayer.lineWidth = 8
CircleLayer.strokeStart = 0
CircleLayer.strokeEnd = 1
Self.View.layer.addSublayer(CircleLayer)
2022, General example of how to actually draw using draw in a UIView.
It's not so easy to properly use UIView#draw.
General beginner tips, you can only draw inside a UIView, it is meaningless otherwise. Further, you can only use the draw commands (.fillEllipse etc) inside the draw call of a UIView.
You almost certainly want to set the intrinsic content size properly. It's important to fully understand how to use this on consumers views, in the two possible situations (a) you are using constraints (b) you are positioning the view by hand in layoutSubviews inside another view.
A huge gotchya is that you cannot draw outside the frame, no matter what. In contrast if you just use lazy vars with a layer to draw a shape (whether dot, circle, etc) it's no problem if you go outside the nominal frame (indeed you often just make the frame size zero so that everything centers easily in your consumer code). But once you start using draw you MUST be inside the frame. This is often confusing as in some cases you "don't know how big your drawing is going to be" until you draw it.
A huge gotchya is, when you are drawing either circles or edges, beginner programmers accidentally cut off half the thickness of that line, due to the fact that draw absolutely can't draw outside the frame. You have to inset the circle or rectangle, by, half the width of the line thickness.
Some code with correct 2022 syntax:
import UIKit
class ExampleDot: UIIView {
// setup ..
// clipsToBounds = false BUT SEE NOTES
// backgroundColor = .clear
override var intrinsicContentSize: CGSize {
return CGSize(width: 40, height: 40)
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
// example of a dot
ctx.setFillColor(UIColor.black.cgColor)
ctx.fillEllipse(in: CGRect(x: 0, y: 0, width: 40, height: 40))
// example of a round circle BUT SEE NOTES
ctx.setStrokeColor(UIColor.systemYellow.cgColor)
ctx.setLineWidth(2)
ctx.strokeEllipse(in: CGRect(x: 1, y: 1, width: 40 - 4, height: 40 - 4))
// example of a smaller inner dot
ctx.setFillColor(UIColor.white.cgColor)
ctx.fillEllipse(in: CGRect(x: 10, y: 10, width: 20, height: 20))
}
}

Resources