Smooth animation CAGradientLayer with long duration - swift

Created CAGradientLayer with a sharp color transition. Position of the color transition changes during the time with using CABasicAnimation.
Everything works, but if I use long duration, animation doesn't produce a smooth change.
Code of gradient creation
override func draw(_ rect: CGRect) {
let path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: 50, height: 50))
path.move(to: CGPoint(x: 75, y: 75))
path.addRect(CGRect(x: 75, y: 75, width: 50, height: 50))
let mask = CAShapeLayer()
mask.path = path
gradient = CAGradientLayer()
gradient.mask = mask
gradient.colors = [UIColor.orange.cgColor, UIColor.blue.cgColor]
gradient.locations = [0, 0]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
gradient.frame = bounds
layer.insertSublayer(gradient, at: 0)
}
Animation code
func play() {
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0, 0]
animation.toValue = [1, 1]
animation.duration = 120
animation.fillMode = .backwards
animation.isRemovedOnCompletion = false
gradient.add(animation, forKey: nil)
}
Demonstration of how the code works
https://i.stack.imgur.com/eUvOo.gif
Are there any options to make the changes smooth with long animation duration?

This looks like a limitation of CAGradientLayer
You can check current progress of CABasicAnimation using layer presentation().
And using CADisplayLink you can check updated value which presentation layer has for each frame, something like this:
...
gradient.add(animation, forKey: nil)
let link = CADisplayLink(target: self, selector: #selector(linkHandler))
link.add(to: .main, forMode: .default)
link.isPaused = false
}
#objc func linkHandler() {
NSLog("\(gradient.presentation()?.locations)")
}
From this test you'll see that value gest updated totally fine, but CAGradientLayer rounds them to around 0.004. Imagine that inside there's code like
locations = locations.map { round($0 * 250) / 250 }
I doubt there's anything you can do about that.
What you can do is use Metal do draw gradient by hand. It's a big and kind of scary topic, but drawing gradient isn't that hard. Check out Rainbows, it's outdated you will have to update the syntax to the current one, but it should be possible

Your draw method is inserting a new gradient layer every time it is called. But this method will be called repeatedly, resulting in multiple layers being inserted. The only thing you should be doing in draw is stroking/filling paths, and in this case, you probably should not implement draw at all.
The insertion of layers does not belong in draw.

Related

UIView With Pointed Edges

I am trying to make a UIView with pointed edges like this. Did some searching around and found some questions with slanting just one edge like this one but can't find an answer with intersecting (points) edges like the one in the picture that dynamically sizes based on the UIView height.
I used Rob's answer to create something like this:
#IBDesignable
class PointedView: UIView
{
#IBInspectable
/// Percentage of the slant based on the width
var slopeFactor: CGFloat = 15
{
didSet
{
updatePath()
}
}
private let shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 0
// with masks, the color of the shape layer doesn’t matter;
// it only uses the alpha channel; the color of the view is
// dictate by its background color
shapeLayer.fillColor = UIColor.white.cgColor
return shapeLayer
}()
override func layoutSubviews()
{
super.layoutSubviews()
updatePath()
}
private func updatePath()
{
let path = UIBezierPath()
// Start from x = 0 but the mid point of y of the view
path.move(to: CGPoint(x: 0, y: bounds.midY))
// Calculate the slant based on the slopeFactor
let slantEndX = bounds.maxX * (slopeFactor / 100)
// Create the top slanting line
path.addLine(to: CGPoint(x: slantEndX, y: bounds.minY))
// Straight line from end of slant to the end of the view
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
// Straight line to come down to the bottom, perpendicular to view
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
// Go back to the slant end position but from the bottom
path.addLine(to: CGPoint(x: slantEndX, y: bounds.maxY))
// Close path back to where you started
path.close()
shapeLayer.path = path.cgPath
layer.mask = shapeLayer
}
}
The end result should give you a view close to what you which can be modified on the storyboard
And can also be created using code, here is a frame example since the storyboard showed its compatibility with autolayout
private func createPointedView()
{
let pointedView = PointedView(frame: CGRect(x: 0,
y: 0,
width: 200,
height: 60))
pointedView.backgroundColor = .red
pointedView.slopeFactor = 50
pointedView.center = view.center
view.addSubview(pointedView)
}

CAShapeLayer disappears while moving

CAShapeLayer disappears while moving to another monitor, but not always
Tried searching for code examples
override func draw(_ dirtyRect: NSRect)
{
//super.draw(dirtyRect)
image?.lockFocus()
print("SelectionRect::draw")
if (shapeLayerIsVisible) {
auxLayer.removeFromSuperlayer()
shapeLayer.removeFromSuperlayer()
}
//let origin = frame.origin
auxLayer = CAShapeLayer()
auxLayer.strokeColor = NSColor.white.cgColor
auxLayer.fillColor = nil
auxLayer.lineWidth = 1.0
//rectSize = CGSize(width: x2 - x1, height: y2 - y1)
let selectionRect = frame //CGRect(x: origin.x, y: origin.y, width: frame.size.width, height: frame.size.height)
let auxPath = CGMutablePath()
//print("x1: \(x1), y1: \(y1), x2: \(x2), y2: \(y2), width: \(rectSize.width), height: \(rectSize.height)")
auxPath.addRect(selectionRect)
auxLayer.path = auxPath
layer?.addSublayer(auxLayer)
shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = NSColor.black.cgColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = 1.0
shapeLayer.lineDashPattern = [5, 5]
let path = CGMutablePath()
path.addRect(selectionRect)
shapeLayer.path = path
let lineDashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
lineDashAnimation.fromValue = 0
lineDashAnimation.toValue = shapeLayer.lineDashPattern?.reduce(0) { $0 + $1.intValue }
lineDashAnimation.duration = 1
lineDashAnimation.repeatCount = Float.greatestFiniteMagnitude
shapeLayer.add(lineDashAnimation, forKey: nil)
shapeLayerIsVisible = true
layer?.addSublayer(shapeLayer)
I've got an 5K iMac with two external 4K monitors (all three scaled to look like 2560x1440 if that matters). With the given code, the NSView is initialized with x: 0, y:0, width: 100, height: 100. All works well, I can drag the Windows around on all three monitors. When I moved the Layer with the mouse to a different position and than drag the window to a different monitor the Shape disappears.
Edit: I fixed it by calling draw(9 at the end of each mouseDragged()-Event and chaninging selectionRect from frame to bounds. It works, but is that a clean solution?
Don't call draw() yourself, per Apple's documentation:
You should never call draw() directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.

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.

CABasicAnimation delay between repeat

The code below creates a "shimmer" effect and works great. (The look of reflected light moving across a glossy surface.) It's currently set to repeat forever which is fine, however, I'd like there to be a pause between each shimmer. I can delay the start of the effect, but I can't seem to figure out how to delay each run. Bonus points if the delay time is random.
func startShimmering() {
let light = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.0).cgColor
let gradient = CAGradientLayer()
gradient.colors = [alpha, light, alpha]
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)
gradient.startPoint = CGPoint(x: 1.0, y: 0.525)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
gradient.locations = [0.1, 0.5, 0.9]
self.layer.mask = gradient
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0.0, 0.1, 0.2]
animation.toValue = [0.8, 0.9, 1.0]
animation.duration = 1.5
animation.repeatCount = HUGE
gradient.add(animation, forKey: "shimmer")
}
As mentioned in Kevin's answer, you can use a CAAnimationGroup to add a delay to the end of your shimmer animation.
The "shimmer" animation will have a duration longer than the group's animation. Any difference between these two durations will be the delay between animations.
Here is the code to do so, ready for a Swift Playground:
class ShimmerView: UIView {
func startShimmering() {
let light = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.0).cgColor
let gradient = CAGradientLayer()
gradient.colors = [alpha, light, alpha]
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)
gradient.startPoint = CGPoint(x: 1.0, y: 0.525)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
gradient.locations = [0.1, 0.5, 0.9]
self.layer.mask = gradient
let shimmer = CABasicAnimation(keyPath: "locations")
shimmer.fromValue = [0.0, 0.1, 0.2]
shimmer.toValue = [0.8, 0.9, 1.0]
shimmer.duration = 1.5
shimmer.fillMode = kCAFillModeForwards
shimmer.isRemovedOnCompletion = false
let group = CAAnimationGroup()
group.animations = [shimmer]
group.duration = 2
group.repeatCount = HUGE
gradient.add(group, forKey: "shimmer")
}
}
let view = ShimmerView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
PlaygroundPage.current.liveView = view
view.backgroundColor = .blue
view.startShimmering()
Here is the end result:
(The gif animates the shimmer three times, which is why every third "shimmer" the delay is shorter.)
I haven't tried this myself but I believe you can wrap your animation in an animation group, set the group's duration to longer than the real animation's duration, and then set the group to repeat.
If that doesn't work, you could use a keypath animation instead, where most of the keypath is a reproduction of the normal animation, and the rest of the keypath just keeps the animation value pinned to either the start or end value.
If you want a random delay, your only choice is to actually run a timer (or use a CAAnimationDelegate) to set up a new animation each time.

Swift: Move UIImage partly along path

I am using this code to move a UIImage along a curve:
// paint curve for sun
let path = UIBezierPath()
let imageSunName = "small_sun.png"
let imageSun = UIImage(named: imageSunName)
let imageView = UIImageView(image: imageSun!)
imageView.frame = CGRect(x: xStart, y: yStart, width: 24, height: 24)
self.view.addSubview(imageView)
path.moveToPoint(CGPoint(x: xStart,y: yStart))
path.addQuadCurveToPoint(CGPoint(x: xEnd, y: yEnd), controlPoint: CGPoint(x: xMiddleTop, y: yMiddleTop))
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path.CGPath
animation.repeatCount = 0
animation.duration = 5.0
imageView.layer.addAnimation(animation, forKey: "animate position along path")
Nevertheless, two issues remain:
I would like to move the image only partly along the path (according to the current time vs sunrise/sunset) - how can this be done?
The image jumps to its origin position after the animation stopped - how can I avoid this?
Cheers
To avoid jump to its original position add:
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
To avoid jumping on animation end, just before starting animation move your image layer to the end position:
imageView.layer.position = CGPoint(x: xEnd, y: yEnd)
To move image partly Im afraid that there is no easy way to do it. An alternate way would be by calculating the endPosition and a path based on sunset/sunrise so you don't have to mess things up with animation time at all