Animate bezier straight lines - ios

I want how to animate a bezier straight line like see-saw. Can somebody please suggest. Reference link for animation how does it should look (https://www.youtube.com/watch?v=bjCx128BZK8).

You don't say how you rendered this UIBezierPath, but if you for example added it as a CAShapeLayer you can just apply a CAKeyframeAnimation to it:
// create simple path
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 50, y: view.bounds.size.height / 2))
path.addLineToPoint(CGPoint(x: view.bounds.size.width - 50, y: view.bounds.size.height / 2))
// create `CAShapeLayer` from that path
let layer = CAShapeLayer()
layer.path = path.CGPath
layer.lineWidth = 10
layer.strokeColor = UIColor.blueColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
view.layer.addSublayer(layer)
// animate it
let animation = CAKeyframeAnimation(keyPath: "transform")
var values = [NSValue]()
for var x: CGFloat = 0.0; x < CGFloat(M_PI * 4); x += CGFloat(M_PI * 4 / 100.0) {
var transform = CATransform3DMakeTranslation(view.frame.size.width/2, view.frame.size.height/2, 0.0)
transform = CATransform3DRotate(transform, sin(x) / 3.0, 0.0, 0.0, 1.0)
transform = CATransform3DTranslate(transform, -view.frame.size.width/2, -view.frame.size.height/2, 0.0)
values.append(NSValue(CATransform3D: transform))
}
animation.duration = 2
animation.values = values
layer.addAnimation(animation, forKey: "transform")
That yields:
Or you could add the CAShapeLayer to a view and then use the block-based UIView animation to rotate the view. The basic idea would be the same.
If you want to do something more sophisticated, you can use CADisplayLink, either updating the path for the CAShapeLayer (as outlined here) or updating the properties used by UIView subclass and then call setNeedsDisplay.

Related

Remove black filled color from shape in ccore animation

I am working on an animation where an image moves with line in a curved path. I am able to draw the line and also move the plane but I am getting a black filled up part in the path. How do I remove it? Please check here
Following is my code to create the animation:
func animate(image: UIView, fromPoint start: CGPoint, toPoint end: CGPoint) {
// The animation
let animation = CAKeyframeAnimation(keyPath: "strokeEnd")
// Animation's path
let path = UIBezierPath()
// Move the "cursor" to the start
path.move(to: start)
path.addLine(to: start)
// Calculate the control points
let c1 = CGPoint(x: end.x - 30, y: start.y)
let c2 = CGPoint(x: end.x, y: start.y - 30)
// Draw a curve towards the end, using control points
path.addCurve(to: end, controlPoint1: c1, controlPoint2: c2)
// Use this path as the animation's path (casted to CGPath)
animation.path = path.cgPath
// The other animations properties
animation.fillMode = CAMediaTimingFillMode.forwards
animation.isRemovedOnCompletion = false
animation.duration = 3.0
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
// Apply it
image.layer.add(animation, forKey: "position")
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = R.color.MyPurple()?.cgColor
shapeLayer.lineWidth = 3
shapeLayer.path = path.cgPath
self.view.layer.addSublayer(shapeLayer)
}
Please add following line:
shapeLayer.fillColor = UIColor.clear.cgColor

CABasicAnimation not scaling around center

I want to perform opacity And Scale effect at same time my animation work perfect but it's position is not proper. i want to perform animation on center.
This is my code.
btn.backgroundColor = UIColor.yellowColor()
let stroke = UIColor(red:236.0/255, green:0.0/255, blue:140.0/255, alpha:0.8)
let pathFrame = CGRectMake(24, 13, btn.bounds.size.height/2, btn.bounds.size.height/2)
let circleShape1 = CAShapeLayer()
circleShape1.path = UIBezierPath(roundedRect: pathFrame, cornerRadius: btn.bounds.size.height/2).CGPath
circleShape1.position = CGPoint(x: 2, y: 2)
circleShape1.fillColor = stroke.CGColor
circleShape1.opacity = 0
btn.layer.addSublayer(circleShape1)
circleShape1.anchorPoint = CGPoint(x: 0.5, y: 0.5)
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2.0, 2.0, 1))
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 1
alphaAnimation.toValue = 0
CATransaction.begin()
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 1.5
animation.repeatCount = .infinity
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleShape1.addAnimation(animation, forKey:"Ripple")
CATransaction.commit()
The problem is that you are not grappling with frames correctly. You say:
let circleShape1 = CAShapeLayer()
But you have forgotten to give circleShape1 a frame! Thus, its size is zero, and very weird things happen when you animate it. Your job in the very next line should be to assign circleShape1 a frame. Example:
circleShape1.frame = pathFrame
That may or may not be the correct frame; it probably isn't. But you need to figure that out.
Then, you need to fix the frame of your Bezier path in terms of the shape layer's bounds:
circleShape1.path = UIBezierPath(roundedRect: circleShape1.bounds // ...
I have never worked with sublayers so I would make it with a subview instead, makes the code a lot easier:
btn.backgroundColor = UIColor.yellow
let circleShape1 = UIView()
circleShape1.frame.size = CGSize(width: btn.frame.height / 2, height: btn.frame.height / 2)
circleShape1.center = CGPoint(x: btn.frame.width / 2, y: btn.frame.height / 2)
circleShape1.layer.cornerRadius = btn.frame.height / 4
circleShape1.backgroundColor = UIColor(red:236.0/255, green:0.0/255, blue:140.0/255, alpha:0.8)
circleShape1.alpha = 1
btn.addSubview(circleShape1)
UIView.animate(withDuration: 1,
delay: 0,
options: [.repeat, .curveLinear],
animations: {
circleShape1.transform = CGAffineTransform(scaleX: 5, y: 5)
circleShape1.alpha = 0.4
}, completion: nil)
You need to create path frame with {0,0} position, and set correct frame to the Layer:
let pathFrame = CGRectMake(0, 0, btn.bounds.size.height/2, btn.bounds.size.height/2)
....
circleShape1.frame = CGRect(x: 0, y: 0, width: pathFrame.width, height: pathFrame.height)
circleShape1.position = CGPoint(x: 2, y: 2)
If you want to create path with {13,24} position you need to change width and height in layer. Your shape should be in center of layer.

CAShapeLayer with gradient

I have a problem with adding gradient to CAShapeLayer. I've created circle layer and I want to add a gradient to it. So, I created a CAGradientLayer and set it frames to layer bounds and mask to layer and it doesn't appear. What can I do?
private func setupCircle() -> CAShapeLayer {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: progressView.frame.size.width / 2.0, y: progressView.frame.size.height / 2.0), radius: (progressView.frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = nil
circleLayer.strokeColor = UIColor.yellowColor().CGColor
circleLayer.backgroundColor = UIColor.yellowColor().CGColor
circleLayer.lineWidth = configurator.lineWidth
circleLayer.strokeEnd = 1.0
return circleLayer
}
private func setupGradient() -> CAGradientLayer {
let gradient = CAGradientLayer()
gradient.colors = [UIColor.clearColor().CGColor, UIColor.yellowColor().CGColor, UIColor.greenColor().CGColor]
gradient.locations = [0.0, 0.25, 1.0]
gradient.startPoint = CGPointMake(0, 0)
gradient.endPoint = CGPointMake(1, 1)
return gradient
}
let circle = setupCircle()
let gradient = setupGradient()
gradient.frame = circle.bounds
gradient.mask = circle
progressView.layer.addSublayer(circle)
progressView.layer.insertSublayer(gradient, atIndex: 0)
EDIT:
I've changed setupCircle method to:
private func setupCircle() -> CAShapeLayer {
let circleLayer = CAShapeLayer()
circleLayer.frame = progressView.bounds.insetBy(dx: 5, dy: 5)
circleLayer.path = UIBezierPath(ovalInRect: CGRectMake(progressView.center.x, progressView.center.y, progressView.bounds.size.width, progressView.bounds.size.height)).CGPath
circleLayer.fillColor = nil
circleLayer.strokeColor = UIColor.yellowColor().CGColor
circleLayer.backgroundColor = UIColor.yellowColor().CGColor
circleLayer.lineWidth = configurator.lineWidth
circleLayer.strokeEnd = 1.0
return circleLayer
}
And here the effect, did I do it properly?:
EDIT 2:
I've changed circleLayer.path = UIBezierPath(ovalInRect: CGRectMake(progressView.center.x, progressView.center.y, progressView.bounds.size.width, progressView.bounds.size.height)).CGPath to circleLayer.path = UIBezierPath(ovalInRect: circleLayer.bounds).CGPath and it's better but still not what I want:
It's ok that you create layers and add them to layer hierarchy in viewDidLoad, but you shouldn't do any frame logic there since layout is not updated at that moment.
Try to move all the code which is doing any frame calculations to viewDidLayoutSubviews.
This should also be done every time layout is updated, so move it from setupCircle to viewDidLayoutSubviews:
let circlePath = UIBezierPath(...)
circleLayer.path = circlePath.cgPath
Edit:
Also I can't see where do you set circleLayer's frame? It's not enough to set it's path. If you have CGRect.zero rect for a mask, it will completely hide it's parent layer.
I would recommend to replace this:
let circlePath = UIBezierPath(arcCenter: CGPoint(x: progressView.frame.size.width / 2.0, y: progressView.frame.size.height / 2.0), radius: (progressView.frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
with this:
circleLayer.bounds = progressView.frame.insetBy(dx: 5, dy: 5)
circleLayer.path = UIBezierPath(ovalIn: circleLayer.bounds).cgPath
This way you'll have both frame and path set. Also be careful about coordinate system. I'm not sure about where is progressView in your view hierarchy, perhaps you'll need it's bounds instead.
Edit 2:
Also you should delete a few lines of code there.
This makes your circle layer completely opaque, it makes the shape itself unvisible.
circleLayer.backgroundColor = UIColor.yellowColor().CGColor
You shouldn't add circle as a sublayer since you're going to use it as a mask:
progressView.layer.addSublayer(circle)

Adding image to a CAShapeLayer Swift 3

I am trying to draw a pie chart with a segment array and an image in the center of each slice , I am have drawn the pie chart , but not able to add an image to the cashapelayer.I refered to the following post Swift: Add image to CAShapeLayer , but it did not solve my issue.
This is what I have tried.
override func draw(_ rect: CGRect) {
//let context = UIGraphicsGetCurrentContext()
let radius = min(frame.size.width,frame.size.height) * 0.5;
let viewCenter = CGPoint(x: frame.size.width * 0.5, y: frame.size.height * 0.5)
let valueCount = segments.reduce(0){ $0 + $1.value}
var startAngle = -CGFloat(M_PI / 2)
for segment in segments {
let endAngle = startAngle + CGFloat(M_PI * 2) * (segment.value)/valueCount
/*context?.move(to: CGPoint(x: viewCenter.x, y: viewCenter.y))
context?.setFillColor(segment.color.cgColor)
context?.setStrokeColor(UIColor.black.cgColor)
context?.setLineWidth(3.0)
context?.addArc(center: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
context?.fillPath()*/
let pieSliceLayer = CAShapeLayer()
let slicePath = UIBezierPath(arcCenter: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
pieSliceLayer.path = slicePath.cgPath
pieSliceLayer.fillColor = segment.color.cgColor
self.layer.addSublayer(pieSliceLayer)
let halfAngle = startAngle + (endAngle - startAngle) * 0.5;
let imagePositionValue = CGFloat(0.67)
let segmentCenter = CGPoint(x:viewCenter.x+radius*imagePositionValue*cos(halfAngle),y:viewCenter.y+radius*imagePositionValue*sin(halfAngle))
//If image is associated , add the image to the section
let imageLayer = CAShapeLayer()
let image = UIImage(named: segment.imageName)
imageLayer.contents = image?.ciImage
imageLayer.frame = CGRect(x: segmentCenter.x - 20, y: segmentCenter.y - 20, width: 20, height: 20)
self.layer.addSublayer(imageLayer)
startAngle = endAngle
}
}
I tried something similar in objective-C and it works fine ,
CALayer *imageLayer = (CALayer *)[[pieLayer sublayers] objectAtIndex:0];
//Adding image
CALayer *layer = [CALayer layer];
layer.backgroundColor = [[UIColor clearColor] CGColor];
layer.bounds = CGRectMake(imageLayer.bounds.origin.x +20 ,
imageLayer.bounds.origin.y + 20, 15, 15);
NSString *imageName = [NSString stringWithString:[[self.goalSettingsModel objectAtIndex:value] valueForKeyPath:#"imageName"]];
layer.contents = (id)[UIImage imageNamed:imageName].CGImage;
[imageLayer addSublayer:layer];
[imageLayer setNeedsDisplay];
I am not sure , if I have missed any settings for the calayer.
After setting the position attribute for the layer, the image was added properly to the shape layer ,
let imageLayer = CALayer()
imageLayer.backgroundColor = UIColor.clear.cgColor
imageLayer.bounds = CGRect(x: centerPoint.x, y: centerPoint.y , width: 15, height: 15)
imageLayer.position = CGPoint(x:centerPoint.x ,y:centerPoint.y)
imageLayer.contents = UIImage(named:segment.imageName)?.cgImage
self.layer.addSublayer(pieSliceLayer)
self.layer.addSublayer(imageLayer)
A couple of things:
First, you only need to update the shape layer when the graph changes (call setNeedsDisplay) or when you have a layout change (viewDidLayoutSubviews). You don't need to implement drawRect unless you are going to do actually drawing. The layering system knowns how to render the shape layer and will render it as necessary.
Second, CAShapeLayer is for shapes. There are actually a whole bunch of CALayers and they all draw different things: https://www.raywenderlich.com/90919/great-calayer-tour-tech-talk-video . In the case of a plain old image, just do what your Objective C code is doing and use a separate CALayer to hold the image instead of CAShapeLayer. Add your image layer as a sublayer on top of or behind your graph shape layer, depending on your z-ordering preference.

CATransform3DMakeRotation anchorpoint and position in Swift

Hi I am trying to rotate a triangle shaped CAShapeLayer. The northPole CAShapeLayer is defined in a custom UIView class. I have two functions in the class one to setup the layer properties and one to animate the rotation. The rotation animate works fine but after the rotation completes it reverts back to the original position. I want the layer to stay at the angle given (positionTo = 90.0) after the rotation animation.
I am trying to set the position after the transformation to retain the correct position after the animation. I have also tried to get the position from the presentation() method but this has been unhelpful. I have read many articles on frame, bounds, anchorpoints but I still cannot seem to make sense of why this transformation rotation is not working.
private func setupNorthPole(shapeLayer: CAShapeLayer) {
shapeLayer.frame = CGRect(x: self.bounds.width / 2 - triangleWidth / 2, y: self.bounds.height / 2 - triangleHeight, width: triangleWidth, height: triangleHeight)//self.bounds
let polePath = UIBezierPath()
polePath.move(to: CGPoint(x: 0, y: triangleHeight))
polePath.addLine(to: CGPoint(x: triangleWidth / 2, y: 0))
polePath.addLine(to: CGPoint(x: triangleWidth, y: triangleHeight))
shapeLayer.path = polePath.cgPath
shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 1.0)
The animate function:
private func animate() {
let positionTo = CGFloat(DegreesToRadians(value: degrees))
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = 0.0
rotate.toValue = positionTo //CGFloat(M_PI * 2.0)
rotate.duration = 0.5
northPole.add(rotate, forKey: nil)
let present = northPole.presentation()!
print("presentation position x " + "\(present.position.x)")
print("presentation position y " + "\(present.position.y)")
CATransaction.begin()
northPole.transform = CATransform3DMakeRotation(positionTo, 0.0, 0.0, 1.0)
northPole.position = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
CATransaction.commit()
}
To fix the problem, in the custom UIView class I had to override layoutSubviews() with the following:
super.layoutSubviews()
let northPoleTransform: CATransform3D = northPole.transform
northPole.transform = CATransform3DIdentity
setupNorthPole(northPole)
northPole.transform = northPoleTransform

Resources