Swift Animate Mask Transition - swift

How can you animate a mask moving down X pixels?
I have a circular mask applied to a black view that creates a spotlight effect. I want to animate the mask transitioning down 100 pixels, but using UIView.animate { mask.transform = CATransform3DTranslate(.init(), 0, 100, 0) } instantly moves it instead of animating the transition.
Here's the mask code:
private lazy var mask: CAShapeLayer = {
let mask = CAShapeLayer()
let path = CGMutablePath()
path.addArc(center: CGPoint(x: 0, y: 0), radius: 40, startAngle: 0, endAngle: 2.0 * .pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: view.frame.size))
mask.backgroundColor = UIColor.black.cgColor
mask.path = path
mask.fillRule = .evenOdd
return mask
}()
overlayView.layer.mask = mask
How would you animate this moving down 100 pixels?

To get the spotlight effect, you'll want to create paths that modify the arc shape and animate between them.
func spotlightPath(arcCenter: CGPoint) -> CGPath {
let path = CGMutablePath()
// move the spotlight
path.addArc(center: CGPoint(x: arcCenter.x, y: arcCenter.y), radius: 40, startAngle: 0, endAngle: 2.0 * .pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: view.frame.size))
return path
}
let startPath = spotlightPath(arcCenter: .zero)
And then later
let endPath = spotlightPath(arcCenter: CGPoint(x: 40, y: 100))
let animation = CABasicAnimation(keyPath: "path")
animation.duration = 1
animation.isRemovedOnCompletion = false
animation.fillMode = .forwards
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animation.toValue = endPath
mask.add(animation, forKey: "path")

Try this Core animation block. CALayer animation is not supported by UIView animation block. To animate mask property we use the path key.
let anim = CABasicAnimation(keyPath: "path")
anim.toValue = createPath(center: .init(x: 100, y: 100))
anim.duration = 1
anim.fillMode = .forwards
anim.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
anim.isRemovedOnCompletion = false
mask.add(anim, forKey: anim.keyPath)

Related

How to launch gradient animation on button tapped?

I'm creating an IOS application. I have 5 buttons in star shapes created with UIBezierPath. And I want fill them when I tapped specific star. For ex. if I tapped 3-rd star then gradient will fill 3 first stars etc.
I have already created view with 5 stars. In the draw view method I have added code for animating gradient and it works fine only when view is launched.
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
UIColor.black.setStroke()
path.lineWidth = 2
let numberOfPoints = 5
var angle: CGFloat = CGFloat.pi / 2
let angleOfIncrement = CGFloat.pi*2/CGFloat(numberOfPoints)
let radius: CGFloat = rect.origin.x + rect.width/2
let offset = CGPoint(x: rect.origin.x + rect.width/2, y: rect.origin.y + rect.height/2)
let midleRadius = radius*0.45
var firstStar = true
for _ in 1...numberOfPoints {
let firstPoint = getPointLocation(angle: angle, radius: midleRadius, offset: offset)
let midlePoint = getPointLocation(angle: angle+angleOfIncrement/2, radius: radius, offset: offset)
let secondPoint = getPointLocation(angle: angle+angleOfIncrement, radius: midleRadius, offset: offset)
if firstStar {
firstStar = false
path.move(to: firstPoint)
path.addLine(to: midlePoint)
path.addLine(to: secondPoint)
}else {
path.addLine(to: firstPoint)
path.addLine(to: midlePoint)
path.addLine(to: secondPoint)
}
angle += angleOfIncrement
}
path.stroke()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
let gradient = CAGradientLayer(layer: layer)
gradient.colors = [UIColor.black.cgColor, UIColor.white.cgColor]
gradient.locations = [1]
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 1, y: 1)
gradient.frame = path.bounds
self.layer.addSublayer(gradient)
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0, 0]
animation.toValue = [0, 1.0]
animation.duration = 3
gradient.add(animation, forKey: nil)
self.layer.mask = shapeLayer
}
I expect that when I tapped 3-rd star then gradient will fill first 3 stars.
You have to separate your drawing code from your animation code, and (btw.) you should also (re-)move the layer creation out of draw().
For the separation move
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0, 0]
animation.toValue = [0, 1.0]
animation.duration = 3
gradient.add(animation, forKey: nil)
into a separate method and call it when needed.
You must also remove the layer creation from draw()because this method is always called if the view needs to be (re-)drawn. This produce a serious memory leak, because for instance every rotation of your iPhone will create a new gradient layer.
You have another issue in your code. Your gradient layer lies over the layer of the view. That cannot work. You may make the gradient layer to the view's layer, and work with mask, to cut the stars out of the gradient.

Resize radius from 0 to 100 with CABasicAnimation

I want to animate a circle. The circle radius should grow from 0 to 100. I tried it with the transform.scale animation. But of course it is not possible to scale a circle with a radius of 0. When I set the radius of the circle to 1 the circle is visible although it shouldn't be at the beginning of the animation.
minimal example:
let circleShape = CAShapeLayer()
let circlePath = UIBezierPath(arcCenter: .zero, radius: 0, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi*2), clockwise: true)
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.brown.cgColor
let circleAnimation = CABasicAnimation(keyPath: "transform.scale")
circleAnimation.fromValue = 0
circleAnimation.toValue = 100
circleAnimation.duration = 1.9
circleAnimation.beginTime = CACurrentMediaTime() + 1.5
circleShape.add(circleAnimation, forKey: nil)
At the end of the animation the radius should stay at the new value.
EDIT:
Thanks to #Rob mayoff
Final code:
let circleShape = CAShapeLayer()
let circlePath = UIBezierPath(arcCenter: .zero, radius: 400, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi*2), clockwise: true)
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.brown.cgColor
let circleAnimation = CABasicAnimation(keyPath: "transform.scale")
circleAnimation.fromValue = 0.0000001
circleAnimation.toValue = 1
circleAnimation.duration = 1.9
circleAnimation.beginTime = CACurrentMediaTime() + 1.5
circleShape.add(circleAnimation, forKey: nil)
circleAnimation.fillMode = .backwards
Probably what you want to do is set the radius of circlePath to your final radius:
let circlePath = UIBezierPath(arcCenter: .zero, radius: 0, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi*2), clockwise: true)
circlePath.clone()
And then animate from a near-zero number to 1.0:
circleAnimation.fromValue = 0.0001
circleAnimation.toValue = 1.0
If you want to have the animation start in the future (by setting beginTime), then you also probably want to set the fill mode so that the fromValue is applied to the layer until the animation starts:
circleAnimation.fillMode = .backwards
You should use a radius greater 0. Then you can scale it down with circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 0.0)
before adding the layer. And then you could start the animation:
let circleShape = CAShapeLayer()
let center = CGPoint(x: view.frame.width / 2, y: view.frame.height / 2)
let circlePath = UIBezierPath(arcCenter: center, radius: 100.0, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi*2), clockwise: true)
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 0.0)
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.brown.cgColor
let circleAnimation = CABasicAnimation(keyPath: "transform.scale")
circleAnimation.fromValue = 0
circleAnimation.toValue = 1
circleAnimation.duration = 5.9
circleAnimation.beginTime = CACurrentMediaTime() + 1.5
circleShape.add(circleAnimation, forKey: nil)
view.layer.addSublayer(circleShape)

How to remove arc border in shadowed UIView with rounded / arc path?

I have ticket View like this
.
My method is I have 2 view, 1 is the ticket itself, and other is for shadow. I have to do this because if I mask the view, it got clipped and the shadow will not appear in the ticket view.
here is the code for create the ticket view:
let shapeLayer = CAShapeLayer()
shapeLayer.frame = someView.bounds
shapeLayer.path = UIBezierPath(roundedRect: someView.bounds,
byRoundingCorners: [UIRectCorner.bottomLeft,UIRectCorner.bottomRight] ,
cornerRadii: CGSize(width: 5.0, height: 5.0)).cgPath
let rect = CGRect(x:0, y:0, width:200, height:100)
let cornerRadius:CGFloat = 5
let subPathSideSize:CGFloat = 25
let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
let leftSubPath = UIBezierPath(arcCenter: CGPoint(x: rect.width / 2, y: 0),
radius: subPathSideSize / 2, startAngle: .pi, endAngle: .pi * 0, clockwise: false)
leftSubPath.close()
let rightSubPath = UIBezierPath(arcCenter: CGPoint(x: rect.width / 2, y: rect.height),
radius: subPathSideSize / 2, startAngle: .pi, endAngle: .pi * 0, clockwise: true)
rightSubPath.close()
path.append(leftSubPath)
path.append(rightSubPath.reversing())
let mask = CAShapeLayer()
mask.frame = shapeLayer.bounds
mask.path = path.cgPath
someView.layer.mask = mask
Notes: SomeView is the TicketView.
And here is the code for adding shadow:
let shadowMask = CAShapeLayer()
shadowMask.frame = shadowView.bounds
shadowMask.path = path.cgPath
shadowMask.shadowOpacity = 0.2
shadowMask.shadowRadius = 4
shadowMask.masksToBounds = false
shadowMask.shadowOffset = CGSize(width: 0, height: 2)
shadowView.backgroundColor = UIColor.clear
shadowView.layer.addSublayer(shadowMask)
The shadow makes arc/rounded corner have border like this one (marked with circle red).
Here is my Playground gist
Do you know how to remove the border in the rounded corner and arc path?
Thank you.
u need to add clipToBounds in this block that you have written.
let mask = CAShapeLayer()
mask.frame = shapeLayer.bounds
mask.path = path.cgPath
someView.clipsToBounds = true
someView.layer.mask = mask
So I think there is different calculation for corner in mask and path. So I used fillColor of the shadowLayer to match the color of the CouponView. And now, the borders are gone.
shadowLayer.fillColor = someView.backgroundColor.cgColor

UIBezierPath circle animation distortion

So, I'm pretty new to animation and BezierPaths. Here's my code. Can you please help me figure out what's causing the distortion?
let circleLayer = CAShapeLayer()
let radius: CGFloat = 100.0
let beginPath = UIBezierPath(arcCenter: view.center, radius: 0, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
let endPath = UIBezierPath(arcCenter: view.center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
circleLayer.fillColor = UIColor.red.cgColor
circleLayer.path = beginPath.cgPath
circleLayer.removeAllAnimations()
let scaleAnimation = CABasicAnimation(keyPath: "path")
scaleAnimation.fromValue = beginPath.cgPath
scaleAnimation.toValue = endPath.cgPath
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 1
alphaAnimation.toValue = 0
let animations = CAAnimationGroup()
animations.duration = 2
animations.repeatCount = .greatestFiniteMagnitude
animations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animations.animations = [scaleAnimation, alphaAnimation]
circleLayer.add(animations, forKey: "animations")
self.view.layer.addSublayer(circleLayer)
Your goal is to make the circle grow from a center point?
The problem you face with arc animations is that the beginning path and ending path must have the same number of points in them. My guess is that with a radius of 0, the system simplifies your starting path to a single point, or even an empty path.
You might want to instead use a starting radius of 0.01.
Another option would be to animate the layer's scale from 0 to 1 and set the size of the image to the desired end size.

Swift: Animate position of a path on a CAShapeLayer

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")