In another question, how to animate was answered:
Draw line animated
I then tried to add a view to animate simultaneously. I want to create two animated paths that meet at the same CGPoint but have different paths to get there. I want both paths to start at the same time and end animation at the same time. My current approach is to create a second UIBezierPath called path2, along with a second CAShapeLayer called shapeLayer2, but the second path is just overriding the first. I'm pretty sure both paths need different CAShapeLayers because each path will have different attributes. It seems like I then need to add the CAShapeLayer instance as a view.layer sublayer but it doesn't seem to be working. What should I be doing differently to achieve the desired result?
Here is what ultimately worked.
func animatePath() {
// create whatever path you want
let path = UIBezierPath()
path.move(to: CGPoint(x: 10, y: 100))
path.addLine(to: CGPoint(x: 200, y: 50))
path.addLine(to: CGPoint(x: 200, y: 240))
// create whatever path you want
let path2 = UIBezierPath()
let bottomStartX = view.frame.maxX - 10
let bottomStartY = view.frame.maxY - 100
path2.move(to: CGPoint(x: bottomStartX, y: bottomStartY))
path2.addLine(to: CGPoint(x: bottomStartX - 100, y: bottomStartY - 100))
path2.addLine(to: CGPoint(x: 200, y: 240))
// create shape layer for that path
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
shapeLayer.lineWidth = 4
shapeLayer.path = path.cgPath
let shapeLayer2 = CAShapeLayer()
shapeLayer2.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
shapeLayer2.strokeColor = UIColor.blue.cgColor
shapeLayer2.lineWidth = 4
shapeLayer2.path = path.cgPath
// animate it
view.layer.addSublayer(shapeLayer)
view.layer.addSublayer(shapeLayer2)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.duration = 2
shapeLayer.add(animation, forKey: "MyAnimation")
let animation2 = CABasicAnimation(keyPath: "strokeEnd")
animation2.fromValue = 0
animation2.duration = 2
shapeLayer2.add(animation2, forKey: "MyAnimation")
// save shape layer
self.shapeLayer = shapeLayer
}
Related
I can clearly see my line, with the right stroke color, and the line is being drawn correctly, but no matter what, the fill color stay white.
I have added this layer to another UIView subclass (custom view )
let shapeLayer = CAShapeLayer()
shapeLayer.frame=CGRect(x: 0, y: 0, width: (size?.width)!, height: size!.height)
shapeLayer.path = path.cgPath //from my bezier path
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = curveLineColor!.cgColor
shapeLayer.lineWidth = 3.0
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineCap = CAShapeLayerLineCap.round
self.layer.addSublayer(shapeLayer)
What else can I try ?
EDIT
here is how I create the path :
let path = UIBezierPath()
var point1:CGPoint!
var point2:CGPoint!
var firstpoint:CGPoint!
for i in 0..<curvePoints.count-1
{
point1 = curvePoints[i]
point2 = curvePoints[i+1]
point1.y=size!.height-point1.y
point2.y=size!.height-point2.y
path.move(to: point1)
path.addLine(to: point2)
if( i == 0 ) {firstpoint=point1}
}
//close the path
path.move(to: point2)
path.addLine(to: CGPoint(x: frame.width, y: frame.height))
path.move(to: CGPoint(x: frame.width, y: frame.height))
path.addLine(to: firstpoint)
path.close()
Turns out if you don't close your line it will not color it, but my line describes a time series and my look like this :
As you can see I close the curve from the bottom, but, because of those triangle are open I can not put color under this line. It works only if I put a line that close all those triangles.
Any suggestions to get a simple time series line filled with a color ?
The issue is with the bezierPath, the start point is getting shifted every time in the loop so path.close() is not able to close the path correctly w.r.t the start point. By removing unnecessary move's it works fine as below,
let path = UIBezierPath()
let curvePoints = [
CGPoint.init(x: 60, y: 280),
CGPoint.init(x: 100, y: 60),
CGPoint.init(x: 150, y: 200),
CGPoint.init(x: 220, y: 100),
CGPoint.init(x: 300, y: 280)
]
path.move(to: curvePoints.first!)
for i in 1..<curvePoints.count {
path.addLine(to: curvePoints[i])
}
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = UIColor.green.cgColor
shapeLayer.lineWidth = 3.0
shapeLayer.lineJoin = CAShapeLayerLineJoin.round // OR kCALineJoinRound
shapeLayer.lineCap = CAShapeLayerLineCap.round // OR kCALineCapRound
self.view.layer.addSublayer(shapeLayer)
Output
I figure it out, you do not have to move the path to the new point every new line you make, it moves there automatically.
so removing path.move(to: point2) , solves the problem !
Thanks for the comments.
I want to fill half of a circle's border using UIBazierpath with gradient color.
Initially I tried with the full circle but it's not working, the gradient always fills the circle but not the border. Is there any way to do this?
Here's what I have so far:
let path = UIBezierPath(roundedRect: rect, cornerRadius: rect.width/2)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 2.0
shape.strokeColor = UIColor.black.cgColor
self.layer.addSublayer(shape)
let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath
gradient.mask = shapeMask
shapeMask.lineWidth = 2
self.layer.addSublayer(gradient)
Edit: Added the image. I want to achieve something like this.
Core graphics doesn't support an axial gradient so you need to draw this out in a more manual way.
Here's a custom view class that draws a circle using the range of HSV colors around the circumference.
class RadialCircleView: UIView {
override func draw(_ rect: CGRect) {
let thickness: CGFloat = 20
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = min(bounds.width, bounds.height) / 2 - thickness / 2
var last: CGFloat = 0
for a in 1...360 {
let ang = CGFloat(a) / 180 * .pi
let arc = UIBezierPath(arcCenter: center, radius: radius, startAngle: last, endAngle: ang, clockwise: true)
arc.lineWidth = thickness
last = ang
UIColor(hue: CGFloat(a) / 360, saturation: 1, brightness: 1, alpha: 1).set()
arc.stroke()
}
}
}
let radial = RadialCircleView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
radial.backgroundColor = UIColor(red: 0.98, green: 0.92, blue: 0.84, alpha: 1) // "antique white"
Copy this into a playground to experiment with the results. The colors don't exactly match your image but it may meet your needs.
I have an array of type [UIBezierPath] that I transform into cgPaths and then animate onto a CAShapeLayer I called shapeLayer. Now for some reason all my paths are upside down, so all the paths get drawn upside down. How can I fix this, I tried a couple of methods but sadly none of them worked... I did however figure out how to scale the path. This is my code to draw the swiftPath, which is a path made up of UIBezierPaths found in the Forms class under the function swiftBirdForm(). Drawing the path is working fine, I just can't figure out how to flip it 180 degrees.
#objc func drawForm() {
var swiftPath = Forms.swiftBirdForm()
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 1
shapeLayer.frame = CGRect(x: -120, y: 120, width: 350, height: 350)
var paths: [UIBezierPath] = swiftPath
guard let path = paths.first else {
return
}
paths.dropFirst()
.forEach {
path.append($0)
}
shapeLayer.transform = CATransform3DMakeScale(0.6, 0.6, 0)
shapeLayer.path = path.cgPath
self.view.layer.addSublayer(shapeLayer)
let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimation.duration = 1.0
strokeEndAnimation.fromValue = 0.0
strokeEndAnimation.toValue = 1.0
shapeLayer.add(strokeEndAnimation, forKey: nil)
}
Using CATransform3D
shapeLayer.transform = CATransform3DMakeScale(1, -1, 1)
Transforming path,
let shapeBounds = shapeLayer.bounds
let mirror = CGAffineTransform(scaleX: 1,
y: -1)
let translate = CGAffineTransform(translationX: 0,
y: shapeBounds.size.height)
let concatenated = mirror.concatenating(translate)
bezierPath.apply(concatenated)
shapeLayer.path = bezierPath.cgPath
Transforming layer,
let shapeFrame = CGRect(x: -120, y: 120, width: 350, height: 350)
let mirrorUpsideDown = CGAffineTransform(scaleX: 1,
y: -1)
shapeLayer.setAffineTransform(mirrorUpsideDown)
shapeLayer.frame = shapeFrame
I have a path and a shape Layer on that I want to draw a line
let path = UIBezierPath()
path.move(to: CGPoint(x: xValue,y: yValue))
path.addLine(to: CGPoint(x: xValue, y: yValue + 300))
// create shape layer for that path
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
shapeLayer.lineWidth = 3
shapeLayer.path = path.cgPath
But I am also animating the drawing of the line
self.chartView.layer.addSublayer(shapeLayer)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.duration = 0.6
shapeLayer.add(animation, forKey: "MyAnimation")
Now to my question:
I also want to animate the position of my path at the meanwhile. So at the moment my line is on the x-Positon of "xValue". I want to move it animated to "xValue - 40.0". I tried it on 2 ways which both didnt work.
use UIView.animate. Problem: The x Position is changing but without an animation:
UIView.animate(withDuration: 3.0) {
var highlightFrame = shapeLayer.frame
highlightFrame.origin.x = (highlightFrame.origin.x) - 40
shapeLayer.frame = highlightFrame
}
add a animation on the shape layer. Nothing happens here
let toPoint:CGPoint = CGPoint(x: -40.0, y: 0.0)
let fromPoint:CGPoint = CGPoint.zero
let movement = CABasicAnimation(keyPath: "movement")
movement.isAdditive = true
movement.fromValue = NSValue(cgPoint: fromPoint)
movement.toValue = NSValue(cgPoint: toPoint)
movement.duration = 0.3
shapeLayer.add(movement, forKey: "move")
Anyone has another solution? Thanks for your help.
let toPoint:CGPoint = CGPoint(x: -40.0, y: 0.0)
let fromPoint:CGPoint = CGPoint.zero
let movement = CABasicAnimation(keyPath: "position") // it should be "position" not "movement"
movement.isAdditive = true
movement.fromValue = NSValue(cgPoint: fromPoint)
movement.toValue = NSValue(cgPoint: toPoint)
movement.duration = 0.3
shapeLayer.add(movement, forKey: "move")
I have a strange question. Even though I did read a lot of tutorials on how to do this, the final result only shows the bezier line, not any shadow whatsoever. My code is pretty simple :
let borderLine = UIBezierPath()
borderLine.moveToPoint(CGPoint(x:0, y: y! - 1))
borderLine.addLineToPoint(CGPoint(x: x!, y: y! - 1))
borderLine.lineWidth = 2
UIColor.blackColor().setStroke()
borderLine.stroke()
let shadowLayer = CAShapeLayer()
shadowLayer.shadowOpacity = 1
shadowLayer.shadowOffset = CGSize(width: 0,height: 1)
shadowLayer.shadowColor = UIColor.redColor().CGColor
shadowLayer.shadowRadius = 1
shadowLayer.masksToBounds = false
shadowLayer.shadowPath = borderLine.CGPath
self.layer.addSublayer(shadowLayer)
What am I doing wrong as I dont seem to see anything wrong but of course I am wrong since no shadow appears. The function is drawRect, basic UIVIew no extra anything in there, x and y are the width and height of the frame. Many thanks in advance!
I take this example straight from my PaintCode-app. Hope this helps.
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Shadow Declarations
let shadow = UIColor.blackColor()
let shadowOffset = CGSizeMake(3.1, 3.1)
let shadowBlurRadius: CGFloat = 5
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(30.5, 90.5))
bezier2Path.addLineToPoint(CGPointMake(115.5, 90.5))
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, (shadow as UIColor).CGColor)
UIColor.blackColor().setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
CGContextRestoreGState(context)
I prefer the way to add a shadow-sublayer. You can easily use the following function (Swift 3.0):
func createShadowLayer() -> CALayer {
let shadowLayer = CALayer()
shadowLayer.shadowColor = UIColor.red.cgColor
shadowLayer.shadowOffset = CGSize.zero
shadowLayer.shadowRadius = 5.0
shadowLayer.shadowOpacity = 0.8
shadowLayer.backgroundColor = UIColor.clear.cgColor
return shadowLayer
}
And finally, you just add it to your line path (CAShapeLayer):
let line = CAShapeLayer()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 50, y: 100))
path.addLine(to: CGPoint(x: 100, y: 50))
line.path = path.cgPath
line.strokeColor = UIColor.blue.cgColor
line.fillColor = UIColor.clear.cgColor
line.lineWidth = 2.0
view.layer.addSublayer(line)
let shadowSubLayer = createShadowLayer()
shadowSubLayer.insertSublayer(line, at: 0)
view.layer.addSublayer(shadowSubLayer)
I am using the shadow properties of my shape layer to add shadow to it. The best part of this approach is that I don't have to provide a path explicitly. The shadow follows the path of the layer. I am also animating the layer by changing path. In that case too the shadow animates seamlessly without a single line of code.
Here is what I am doing (Swift 4.2)
shapeLayer.path = curveShapePath(postion: initialPosition)
shapeLayer.strokeColor = UIColor.clear.cgColor
shapeLayer.fillColor = shapeBackgroundColor
self.layer.addSublayer(shapeLayer)
if shadow {
shapeLayer.shadowRadius = 5.0
shapeLayer.shadowColor = UIColor.gray.cgColor
shapeLayer.shadowOpacity = 0.8
}
The curveShapePath method is the one that returns the path and is defined as follows:
func curveShapePath(postion: CGFloat) -> CGPath {
let height: CGFloat = 37.0
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0)) // start top left
path.addLine(to: CGPoint(x: (postion - height * 2), y: 0)) // the beginning of the trough
// first curve down
path.addCurve(to: CGPoint(x: postion, y: height),
controlPoint1: CGPoint(x: (postion - 30), y: 0), controlPoint2: CGPoint(x: postion - 35, y: height))
// second curve up
path.addCurve(to: CGPoint(x: (postion + height * 2), y: 0),
controlPoint1: CGPoint(x: postion + 35, y: height), controlPoint2: CGPoint(x: (postion + 30), y: 0))
// complete the rect
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: 0, y: self.frame.height))
path.close()
return path.cgPath
}