SpriteKit - Animate SKShapeNode Shape Path - ios

Currently I am using Core Graphics for a shape and to transform the shape in to a different one with CAShapeLayer and CABasicAnimation path animation.
However due to the complexity of the game, If were to step in to SpritKit, using SKShapeNode, (discarding CAShapeLayer and using SKShapeNode) would I be able to smoothly animate it in to a different shape?
I did not see a SKAction method that would let you change the path of a SKShapeNode.
Thanks in advance.

Well. Happy holidays.
The simplest way is to use the CALayerAnimation to teach the SKNode how to action like this :
class ViewController: UIViewController {
#IBOutlet weak var skview: SKView!
var path1: CGPath!
var path2: CGPath!
override func viewDidLoad() {
super.viewDidLoad()
path1 = CGPath.init(rect: CGRect.init(x: 0, y: 0, width: 100, height: 100), transform: nil)
path2 = CGPath.init(rect: CGRect.init(x: 0, y: 0, width: 250, height: 400), transform: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let shapeLayer = CAShapeLayer()
self.view.layer.addSublayer(shapeLayer)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.path = path1
let anim = CABasicAnimation.init(keyPath: "path")
anim.duration = 1.0
anim.fromValue = path1
anim.toValue = path2
anim.isRemovedOnCompletion = false
let shapeNode = SKShapeNode.init(path: path1)
shapeNode.fillColor = UIColor.green
skview.scene?.addChild(shapeNode)
shapeLayer.add(anim, forKey:
"prepanimation")
shapeNode.run(SKAction.customAction(withDuration: anim.duration, actionBlock: { (node, timeDuration) in
(node as! SKShapeNode).path =
shapeLayer.presentation()?.path
}))
}
}
If you path is too big and an optimum way is to consider converting CABasicAnimation to CAKeyFrameAnimation approach.
From the above process you can extract a pair (time, presentation_Path) at design time. Then assign back during the runtime in SKCustomAction. Please refer to SKKeyframeSequence to get the idea (not exactly but similar animation).

Related

merge two CAShaplayer with transparent in Swift5?

We have created two CAShapeLayer and we have animated them by CABasicAnimation changing position like fromValue to toValue so far code works as excepted.
Two layers meeting at some points while animating, its moving one over another seems overlapping. We need to achieve like below image but we have got different output.
Desired output:
Output at Loading view::
Result we got after animating layers:
Code Below:
class MovingAnimationVC: UIViewController {
let layerSize = CGSize(width: 100, height: 100)
private var layerWidth : CGFloat = 100
private var layerHeight : CGFloat = 100
var circleA : CAShapeLayer! = nil
var circleB : CAShapeLayer! = nil
lazy var aPosition = CGPoint(x: -layerWidth/2 + 30, y: 100)
lazy var bPosition = CGPoint(x: (self.view.frame.width - layerWidth / 2) - 30 , y: 400)
override func viewDidLoad() {
super.viewDidLoad()
if circleA == nil{
circleA = CAShapeLayer()
let pa = UIBezierPath(ovalIn: CGRect(origin: aPosition, size: layerSize))
circleA.path = pa.cgPath
circleA.fillColor = UIColor.orange.cgColor
view.layer.addSublayer(circleA)
}
if circleB == nil{
circleB = CAShapeLayer()
let pa = UIBezierPath(ovalIn: CGRect(origin: bPosition, size: layerSize))
circleB.path = pa.cgPath
circleB.fillColor = UIColor.orange.cgColor
view.layer.addSublayer(circleB)
}
}
override func viewDidAppear(_ animated: Bool) {
animateCircleA()
animateCircleB()
}
fileprivate func animateCircleA(){
lazy var startPointA = CGPoint(x: -layerWidth/2 + 30, y: 0)
lazy var endPointA = CGPoint(x: (self.view.frame.width - layerWidth / 2), y: 300)
let animate = CABasicAnimation(keyPath: "position")
animate.timingFunction = CAMediaTimingFunction(name: .linear)
animate.fromValue = NSValue(cgPoint: startPointA)
animate.toValue = NSValue(cgPoint: endPointA)
animate.repeatCount = 2
animate.duration = 5.0
circleA.add(animate, forKey: "position")
}
fileprivate func animateCircleB(){
lazy var startPointB = CGPoint(x: 0, y: 0)
lazy var endPointB = CGPoint(x:-(self.view.frame.width - layerWidth / 2) - 30, y: -(self.view.frame.width - layerWidth / 2) + 30)
let animate = CABasicAnimation(keyPath: "position")
animate.timingFunction = CAMediaTimingFunction(name: .linear)
animate.fromValue = NSValue(cgPoint: startPointB)
animate.toValue = NSValue(cgPoint: endPointB)
animate.repeatCount = 2
animate.duration = 5.0
circleB.add(animate, forKey: "position")
}
}
Kindly suggest me right way to get started.
How to make both layer transparent while crossing each other?
The easiest way is to just set the alphas of the layers, but if you don't want the layers to be transparent, then that means you want a different blend mode for the layers.
According to this question, to change the blend mode of a layer, you can set CALayer.compositingFilter. From your desired output, it seems like the screen blend mode is appropriate:
circleA.compositingFilter = "screenBlendMode"
circleA.compositingFilter = "screenBlendMode"
Note that you should add your layers to a view with a transparent background, otherwise the background color of the view is also blended with the circles' colours. This view can be added as a subview of whatever view you were originally going to put the circles in, filling its entire bounds.
someView.backgroundColor = .clear
someView.layer.addSublayer(circleA)
someView.layer.addSublayer(circleB)

Group Animation in ios

I'm making a custom loader which has circular shaped layer inside and It will animate in two way. First shape will animate pulsing like scaling it's radius increase and decrease with infinite time and in same time it will rotate inside the view with around the center of view. But now my group animation does't work properly, view didn't rotate full radius and scaling didn't worked
here's my code review and tell me where I'm doing mistake.
class ViewController: UIViewController {
#IBOutlet weak var loaderView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//circularLoader()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
drawCircularLoader()
}
func drawCircularLoader(){
let width = loaderView.bounds.width
let halfWidth = width / 2
let size = CGSize(width: halfWidth / 2, height: halfWidth / 2)
let rect = CGRect(x: halfWidth - (size.width / 2), y: (halfWidth / 2) - (size.height / 2), width: size.width, height: size.height)
let path = UIBezierPath(ovalIn: rect)
let layer = CAShapeLayer()
layer.frame = rect
layer.fillColor = UIColor.black.cgColor
layer.path = path.cgPath
loaderView.layer.addSublayer(layer)
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.fromValue = 0
rotation.toValue = 2.0 * .pi
rotation.duration = 1.5
layer.add(rotation, forKey: nil)
let scaling = CABasicAnimation(keyPath: "transform.scale")
scaling.toValue = 1.2
scaling.duration = 0.3
scaling.autoreverses = true
let group = CAAnimationGroup()
group.animations = [rotation, scaling]
group.repeatCount = .infinity
layer.add(group, forKey: nil)
}
}
The immediate problem is that the animation group has no duration. It needs a duration long enough for all its child animations to complete. Otherwise everything just stops after .2 seconds (the default). Try giving the group a duration of 1.5.
In a broader sense I doubt whether your overall goal is a good use of an animation group at all. But that's a different matter. Plus you have two transform animations; they might be interfering with each other (transform is one animatable property), so a different approach might be needed.

Animating a circular progress circle smoothly via buttons

I am experiencing odd visual quirks with my progress circle. I would like the green circle (CAShapeLayer) to smoothly animate in increments of fifths. 0/5 = no green circle. 5/5 = full green circle. The problem is the green circle is animating past where it should be, then abruptly shrinks back to the proper spot. This happens when both the plus and minus button are pressed. There is a gif below demonstrating what is happening.
The duration of each animation should last 0.25 seconds, and should smoothly animate both UP and DOWN (depending if the plus or minus button is pressed) from wherever the animation ended last (which is currently not happening.)
In my UIView, I draw the circle, along with the method to animate the position of the progress:
class CircleView: UIView {
let progressCircle = CAShapeLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func draw(_ rect: CGRect) {
let circlePath = UIBezierPath(ovalIn: self.bounds)
progressCircle.path = circlePath.cgPath
progressCircle.strokeColor = UIColor.green.cgColor
progressCircle.fillColor = UIColor.red.cgColor
progressCircle.lineWidth = 10.0
// Add the circle to the view.
self.layer.addSublayer(progressCircle)
}
func animateCircle(circleToValue: CGFloat) {
let fifths:CGFloat = circleToValue / 5
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = 0.25
animation.fromValue = fifths
animation.byValue = fifths
animation.fillMode = kCAFillModeBoth
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
progressCircle.strokeEnd = fifths
// Create the animation.
progressCircle.add(animation, forKey: "strokeEnd")
}
}
In my VC:
I init the circle and starting point with:
let myDrawnCircle = CircleView()
var startingPointForCircle = CGFloat()
viewDidAppear:
startingPointForCircle = 0.0
myDrawnCircle.frame = CGRect(x: 100, y: 100, width: 150, height: 150)
myDrawnCircle.backgroundColor = UIColor.white
myDrawnCircle.animateCircle(circleToValue: startingPointForCircle)
self.view.addSubview(myDrawnCircle)
textLabel.text = "\(startingPointForCircle)"
And the actual buttons that do the cool animating:
#IBAction func minusButtonPressed(_ sender: UIButton) {
if startingPointForCircle > 0 {
startingPointForCircle -= 1
textLabel.text = "\(startingPointForCircle)"
myDrawnCircle.animateCircle(circleToValue: startingPointForCircle)
}
}
#IBAction func plusButtonPressed(_ sender: UIButton) {
if startingPointForCircle < 5 {
startingPointForCircle += 1
textLabel.text = "\(startingPointForCircle)"
myDrawnCircle.animateCircle(circleToValue: startingPointForCircle)
}
}
Here's a gif showing you what's going on with the jerky animations.
How do I make my animations smoothly animate TO the proper value FROM the proper value?
My guess is it has something to do with using a key path. I don't know how exactly to fix it for using a key path, but you could try a different tack, using a custom view, and animating the value passed to the method used for drawing an arc.
The code below was generated by PaintCode. The value passed for arc specifies the point on the circle to draw the arc to. This is used in the drawRect method of a custom UIView. Make a CGFloat property of the custom view and simply change that value, and call setNeedsDisplay on the view after your animation code.
func drawCircleProgress(frame frame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40), arc: CGFloat = 270) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let white = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
let white50 = white.colorWithAlpha(0.5)
//// Oval Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, frame.minX + 20, frame.minY + 20)
CGContextRotateCTM(context, -90 * CGFloat(M_PI) / 180)
let ovalRect = CGRect(x: -19.5, y: -19.5, width: 39, height: 39)
let ovalPath = UIBezierPath()
ovalPath.addArcWithCenter(CGPoint(x: ovalRect.midX, y: ovalRect.midY), radius: ovalRect.width / 2, startAngle: 0 * CGFloat(M_PI)/180, endAngle: -arc * CGFloat(M_PI)/180, clockwise: true)
white.setStroke()
ovalPath.lineWidth = 1
ovalPath.stroke()
CGContextRestoreGState(context)
}
The desired results were as simple as commenting out fromValue / byValue in the animateCircle method. This was pointed out by #dfri - "set both fromValue and toValue to nil then: "Interpolates between the previous value of keyPath in the target layer’s presentation layer and the current value of keyPath in the target layer’s presentation layer."
//animation.fromValue = fifths
//animation.byValue = fifths

CAShapeLayer is not touchable?

I created a CAShapeLayer and added it as a subLayer.
Then I overridden the:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
And it get called successfully, but after I move this layer using CABasicAnimation.
It's not longer touchable.
The strange thing is that the original empty place of the CAShapeLayer is touchable after the animation finishes.
The structure of the view is as follows:
I subclass UIView and add to it the layer, let's name it view X.
Then I take view X and add it to anther view.
Then I animate view X using CABasicAnimation
Code:
class AIFloatingMenuItem: UIView
{
var image = UIImage()
var color = UIColor.brown
var location:CGPoint?
var fontName:String?
var text:String?
let rectShape = CAShapeLayer()
convenience init(title:String, img:UIImage, bgColor:UIColor)
{
self.init(frame: CGRect(x: 0, y: 0, width: ITEM_SIZE, height: ITEM_SIZE))
self.image = img
self.color = bgColor
self.drawCircle()
backgroundColor = UIColor.red
}
override init(frame: CGRect)
{
super.init(frame: frame)
}
//MARK: - Drawing -
func drawCircle()
{
rectShape.anchorPoint = CGPoint(x:0.5 , y:0.5)
rectShape.fillColor = color.cgColor
let path = UIBezierPath(arcCenter: CGPoint(x: ITEM_SIZE/2, y: ITEM_SIZE/2), radius: ITEM_SIZE/2, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
rectShape.path = path.cgPath
layer.addSublayer(rectShape)
}
}
class AIFloatingMenu: UIView, CAAnimationDelegate
{
var item:AIFloatingMenuItem?
override func awakeFromNib()
{
super.awakeFromNib()
animateItem1()
}
func animateItem1()
{
item = AIFloatingMenuItem(title: "title", img: UIImage(named : "icon-plus")!, bgColor: .green)
let itemsInitialPostition = CGPoint(x: 250, y: 300)
item?.layer.position = itemsInitialPostition
self.addSubview(item!)
drawAnimateY(end: CGPoint(x: item!.layer.position.x, y: 300), isEnd: false, item: item!, delay: 0.5)
}
func drawAnimateY(end:CGPoint, isEnd:Bool, item:AIFloatingMenuItem, delay:Double)
{
let pathAnimation = CASpringAnimation(keyPath: "position")
pathAnimation.damping = 13
CATransaction.begin()
CATransaction.setCompletionBlock
{
}
pathAnimation.delegate = self
pathAnimation.duration = 1.5
pathAnimation.fromValue = item.layer.position
pathAnimation.toValue = end
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.isRemovedOnCompletion = false
pathAnimation.beginTime = CACurrentMediaTime() + delay
item.layer.add(pathAnimation, forKey: nil)
CATransaction.commit()
}
}
I add a view in the storyboard and set it's class to AIFloatingMenu.
I have been able to solve my issue by changing the position of the item being animated to the destination location after the item finishes the Animation:
func drawAnimateY(end:CGPoint, isEnd:Bool, item:AIFloatingMenuItem, delay:Double)
{
let pathAnimation = CASpringAnimation(keyPath: "position")
pathAnimation.damping = 13
CATransaction.begin()
CATransaction.setCompletionBlock
{
item.layer.position = end// changing the position of item to the destination location
}
pathAnimation.delegate = self
pathAnimation.duration = 1.5
pathAnimation.fromValue = item.layer.position
pathAnimation.toValue = end
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.isRemovedOnCompletion = false
pathAnimation.beginTime = CACurrentMediaTime() + delay
item.layer.add(pathAnimation, forKey: nil)
CATransaction.commit()
}

CALayer circle mask animation incorrect behaviour + Swift

I have been trying to do this animation for a couple of days now. I am trying to animate the size of my mask, basically taking a large circle (mask) and shrinking it.
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animateMask()
}
func presentMaskScreenWithAnimation () {
//Setup Mask Layer
let bounds = myView.bounds
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.fillColor = UIColor.brown.cgColor
//CropCircle Out of mask Layer
let initialCircle = CGRect(x: 10, y: 10, width: 300, height: 300)
let path = UIBezierPath(roundedRect: initialCircle, cornerRadius: initialCircle.size.width/2)
path.append(UIBezierPath(rect: bounds))
maskLayer.path = path.cgPath
maskLayer.fillRule = kCAFillRuleEvenOdd
myView.layer.mask = maskLayer
//Define new circle path
let circlePath2 = CGRect(x: 50, y: 50, width: 100, height: 100)
let path2 = UIBezierPath(roundedRect: circlePath2, cornerRadius: circlePath2.size.width/2)
//Create animation
let anim = CABasicAnimation(keyPath: "path")
anim.fromValue = path.cgPath
anim.toValue = path2.cgPath
anim.duration = 3.0
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
maskLayer.add(anim, forKey: nil)
}
This code sets up the mask and begins to animate it however it inverts the entire maskLayer, I am trying to just animate the path of the circle, Large -> Small
Start
Finished
Add path2.append(UIBezierPath(rect: bounds)) after let path2 = UIBezierPath(roundedRect: circlePath2, cornerRadius: circlePath2.size.width/2). Also do not forget to do maskLayer.path = path2.cgPath at the end, if you want the shrinking mask stays after animation.

Resources