how to move position of shape layer (swift4) - ios

My code right now uses a circular progress view and it places in dead center of the screen. I need this exact circular progress view to move about 150 pixels down the x axis.
import UIKit
class ViewController: UIViewController {
let shapeLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let center = view.center
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
view.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
view.layer.addSublayer(shapeLayer)
}

You can try , you say down Y
let center = CGPoint(x:view.center.x,y:view.center.y + 150)
Or right x
let center = CGPoint(x:view.center.x + 150 ,y:view.center.y)

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.

How draw a circular progress bar with CAShapLayer and auto layout constraints

I'm drawing a circular progress bar using CAShapeLayer, I can produce it only if I center it on my view. Now I want to constraint it to the trailing edge of my card view. Below is my code:
let center = cardView.center
//track layer
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.gray.cgColor
trackLayer.strokeEnd = 1
trackLayer.lineCap = kCALineCapRound
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineWidth = 5
cardView.layer.addSublayer(trackLayer)
//progress Layer
let shapeLayer = CAShapeLayer()
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.yellow.cgColor
//NumberFormatter().number(from: percentageUsed) as! CGFloat
shapeLayer.strokeEnd = 0.6
shapeLayer.lineCap = kCALineCapRound
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 5
cardView.layer.addSublayer(shapeLayer)
Now I wish i could do something like
shapeLayer.leadingAnchor.constraint(equalTo: cardVeiw.leadingAnchor, constant: 20).isActive = true

Custom circular progress view in awakeFromNib

I have created circle progress view using UIBezierPath and CAShapeLayer with following code.
let center = self.center
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
self.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
self.layer.addSublayer(shapeLayer)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
If I put that code in my viewDidLoad it works fine. However, when I add UIView from storyboard and set its class to custom class then copy all codes to that custom UIView class and call it in awakeFromNib function it is not working what could be the reason? And how can I use above code with custom UIView class?
Orange view should be my custom view I have added leading, trailing, bottom and fixed height constraint it but it looks like above. Does not circle view need to place center of orange view?
Actually it works but it has wrong position. The position in this case is out of your view so you can't see it. It makes you think that your code doesn't work.
If you want to have circle in the center of your view. Put the code in awakeFromNib and calculate center your self, don't use self.center
override func awakeFromNib() {
let center = CGPoint.init(x: frame.width / 2, y: frame.height / 2)
let trackLayer = CAShapeLayer()
let shapeLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
self.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
self.layer.addSublayer(shapeLayer)
}
Result

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)

Can't put circular layer that surrounds imageView on different iPhone devices

How can I fix this issue?
The image is set with constraints in the storyboard; the other circle is set with these lines of code:
let centerY = profileImage.center.y+20+(self.navigationController?.navigationBar.frame.size.height)!
let centerX = profileImage.center.x
let center = CGPoint(x: centerX, y: centerY)
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: (profileImage.frame.width/2)+2, startAngle: -CGFloat.pi-CGFloat.pi/2, endAngle: CGFloat.pi/2, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = Functions.hexStringToUIColor(hex: "#3859B9").cgColor
trackLayer.lineWidth = 3
trackLayer.lineCap = kCALineCapRound
trackLayer.fillColor = UIColor.clear.cgColor
view.layer.addSublayer(trackLayer)
On iPhone 7 (the one on the right) seems to be right.
Using fixed values for navigation's or status' bar height will lead to such errors. You should position your layer according to the image view. For that you can simply assign the frame of the image view to your layer:
trackLayer.frame = profileImage.frame
Since the layout may change for several reasons (e.g. device rotation), you should do this in viewDidLayoutSubviews of your view controller.
Since the frame of the layer is now smaller than in your example, you should create the center with:
let center = CGPoint(x: profileImage.bounds.midX, y: profileImage.bounds.midY)
override func viewDidLayoutSubviews() {
let centerY = profileImage.center.y+20+(self.navigationController?.navigationBar.frame.size.height)!
let centerX = profileImage.center.x
let center = CGPoint(x: centerX, y: centerY)
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: (profileImage.frame.width/2)+2, startAngle: -CGFloat.pi-CGFloat.pi/2, endAngle: CGFloat.pi/2, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = Functions.hexStringToUIColor(hex: "#3859B9").cgColor
trackLayer.lineWidth = 3
trackLayer.lineCap = kCALineCapRound
trackLayer.fillColor = UIColor.clear.cgColor
view.layer.addSublayer(trackLayer)
}
OR in write the code in viewDidAppear without delay
This would fix the issue.
Add the layer to profileImage.layer.
trackLayer.frame = profileImage.bounds
Full code should be like this:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let center = CGPoint(x: profileImage.bounds.midX,
y: profileImage.bounds.midY)
let trackLayer = CAShapeLayer()
trackLayer.frame = profileImage.frame
let circularPath = UIBezierPath(arcCenter: center,
radius: (profileImage.frame.width / 2) + 2,
startAngle: -CGFloat.pi - CGFloat.pi / 2,
endAngle: CGFloat.pi / 2, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = Functions.hexStringToUIColor(hex: "#3859B9").cgColor
trackLayer.lineWidth = 3
trackLayer.lineCap = kCALineCapRound
trackLayer.fillColor = UIColor.clear.cgColor
profileImage.layer.addSublayer(trackLayer)
}
Using interface builder:
Drag UIView and drop above the imageview
Change view custom class to CirculerProgressView
Set center X and Y constraints with imageview center
Set height and width constraints(greater then imageView height & width)
#IBDesignable class CirculerProgressView: UIView {
override class var layerClass: AnyClass {
return CAShapeLayer.self
}
override func draw(_ rect: CGRect) {
super.draw(rect)
setupLayer()
}
private func setupLayer() {
let trackLayer = layer as! CAShapeLayer
let center = CGPoint(x: frame.width/2, y: frame.height/2)
let circularPath = UIBezierPath(arcCenter: center, radius: frame.width/2, startAngle: -CGFloat.pi-CGFloat.pi/2, endAngle: CGFloat.pi/2, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.blue.cgColor
trackLayer.lineWidth = 3
trackLayer.lineCap = kCALineCapRound
trackLayer.fillColor = UIColor.clear.cgColor
}}

Resources