Animate CAShapeLayer & Shadow independently - ios

I have a 'UIView' Subclass called 'HexagonView' in which I create a layer to display a Hexagon. I then add another layer with the same path as shadow layer. I had to do it this way since I could not display a shadow outside of the 'layer.mask' Shape.
My goal is to animate a 360° rotation of the shape, while the shadow stays on it's position instead of moving around with the rotation.
See example image
This is the code I have so far:
#IBDesignable class HexagonView: UIView {
override func prepareForInterfaceBuilder()
{
super.prepareForInterfaceBuilder()
configureLayer()
addShadow()
}
override init(frame: CGRect)
{
super.init(frame: frame)
configureLayer()
addShadow()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
configureLayer()
addShadow()
}
func configureLayer()
{
let maskLayer = CAShapeLayer()
maskLayer.fillRule = kCAFillRuleEvenOdd
maskLayer.frame = bounds
UIGraphicsBeginImageContext(frame.size)
maskLayer.path = getHexagonPath().cgPath
UIGraphicsEndImageContext()
layer.addSublayer(maskLayer)
}
private func getHexagonPath() -> UIBezierPath
{
let width = frame.size.width
let height = frame.size.height
let padding = width * 1 / 8 / 2
let path = UIBezierPath()
path.move(to: CGPoint(x: width / 2, y: 0))
path.addLine(to: CGPoint(x: width - padding, y: height / 4))
path.addLine(to: CGPoint(x: width - padding, y: height * 3 / 4))
path.addLine(to: CGPoint(x: width / 2, y: height))
path.addLine(to: CGPoint(x: padding, y: height * 3 / 4))
path.addLine(to: CGPoint(x: padding, y: height / 4))
path.close()
return path
}
func addShadow()
{
let s = CAShapeLayer()
s.fillColor = backgroundColor?.cgColor
s.frame = layer.bounds
s.path = getHexagonPath().cgPath
layer.backgroundColor = UIColor.clear.cgColor
layer.addSublayer(s)
layer.masksToBounds = false
layer.shadowColor = AppAppearance.Colors.labelBackground.cgColor
layer.shadowOffset = CGSize(width: 5, height: 10)
layer.shadowOpacity = 0.5
layer.shadowPath = getHexagonPath().cgPath
layer.shadowRadius = 0
}
func rotate(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil)
{
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
if let delegate = completionDelegate as? CAAnimationDelegate {
rotateAnimation.delegate = delegate
}
layer.add(rotateAnimation, forKey: nil)
}
}
How can I achieve the shadow rotation on its starting position rather than having it attached to the white layer.

Related

Swift UIBezierPath starting offset from where it should

I have a Button that hides when pressed and instead an animation is shown that fills from left to right, indicating a wait time.
I have the following class which handles the animation:
//MARK: - Class: LinearProgressBarButtonView
class LinearProgressBarButtonView: UIView {
private var myWidth: CGFloat!
private var myHeight: CGFloat!
init(frame: CGRect, width: CGFloat, height: CGFloat) {
super.init(frame: frame)
myWidth = width
myHeight = height
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private var lineLayer = CAShapeLayer()
private var progressLayer = CAShapeLayer()
func createLinePath() {
// created linePath for lineLayer and progressLayer
let rect = CGRect(x: 0, y: 0, width: myWidth, height: myHeight)
let linePath = UIBezierPath()
linePath.move(to: CGPoint(x: 0.0, y: rect.height/2))
linePath.addLine(to: CGPoint(x: myWidth, y: rect.height/2))
// lineLayer path defined to circularPath
lineLayer.path = linePath.cgPath
// ui edits
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.lineCap = .square
lineLayer.lineWidth = myHeight
lineLayer.strokeEnd = 1.0
lineLayer.strokeColor = colors.Blue.cgColor
// added circleLayer to layer
layer.addSublayer(lineLayer)
// progressLayer path defined to circularPath
progressLayer.path = linePath.cgPath
// ui edits
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .square
progressLayer.lineWidth = myHeight
progressLayer.strokeEnd = 0
progressLayer.strokeColor = colors.red.cgColor
// added progressLayer to layer
layer.addSublayer(progressLayer)
}
func progressAnimation(duration: TimeInterval) {
// created circularProgressAnimation with keyPath
let linearProgressAnimation = CABasicAnimation(keyPath: "strokeEnd")
// set the end time
linearProgressAnimation.duration = duration
linearProgressAnimation.toValue = 1.0
linearProgressAnimation.fillMode = .forwards
linearProgressAnimation.isRemovedOnCompletion = true
progressLayer.add(linearProgressAnimation, forKey: "progressAnim")
}
func endAnimation(){
progressLayer.removeAllAnimations()
}
}
I have set all necessary constraints, which are all correct. Using
linearProgressBarButtonView = LinearProgressBarButtonView(frame: .zero, width: bookButton.frame.width, height: bookButton.frame.height) linearProgressBarButtonView.createLinePath()
I can create the view and later add it as a subview.
I can now use linearProgressBarButtonView.progressAnimation(duration: linearViewDuration) to start the animation, which works exactly as it should. However, the animation does not seem to start at x = 0, but further along the way (somewhere at around 15%). Here is a screenshot of the first second of the animation, which is supposed to last 60 seconds:
I can't seem to figure out why. As far as I understand, it should start from x = 0. And the width should be the exact same width as the view has, which I pass when generating the animated view. Why is it starting with an offset then?
The main problem is:
lineLayer.lineCap = .square
// and
progressLayer.lineCap = .square
Those need to be .butt
When set to .square one-half the line-width will be "added" on each end. Here, the line path goes from 0,20 to 260,20, with a .lineWidth = 40:
You can easily see what's going on by setting layer.borderWidth = 1 on your view ... it will look similar to this:
So, that change should fix your issue.
However, I'd suggest -- instead of saving width/height and having to call createLinePath(), move that code into layoutSubviews(). That will always keep your line path correct, even if you change the frame at a later point:
class LinearProgressBarButtonView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
layer.addSublayer(lineLayer)
layer.addSublayer(progressLayer)
}
private var lineLayer = CAShapeLayer()
private var progressLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
let linePath = UIBezierPath()
linePath.move(to: CGPoint(x: bounds.minX, y: bounds.midY))
linePath.addLine(to: CGPoint(x: bounds.maxX, y: bounds.midY))
lineLayer.path = linePath.cgPath
// ui edits
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.lineCap = .butt
lineLayer.lineWidth = bounds.height
lineLayer.strokeEnd = 1.0
lineLayer.strokeColor = UIColor.systemBlue.cgColor
progressLayer.path = linePath.cgPath
// ui edits
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .butt
progressLayer.lineWidth = bounds.height
progressLayer.strokeEnd = 0.0
progressLayer.strokeColor = UIColor.systemRed.cgColor
}
func progressAnimation(duration: TimeInterval) {
// created ProgressAnimation with keyPath
let linearProgressAnimation = CABasicAnimation(keyPath: "strokeEnd")
// set the end time
linearProgressAnimation.duration = duration
linearProgressAnimation.fromValue = 0.0
linearProgressAnimation.toValue = 1.0
linearProgressAnimation.fillMode = .forwards
linearProgressAnimation.isRemovedOnCompletion = true
progressLayer.add(linearProgressAnimation, forKey: "progressAnim")
}
func endAnimation(){
progressLayer.removeAllAnimations()
}
}

circle with dash lines uiview

I am trying to make a circle with dash lines. I am able to make lines in rectangle but I don't know how to make these in circle. Here is answer I got but it's in Objective-C: UIView Draw Circle with Dotted Line Border
Here is my code which makes a rectangle with dashed lines.
func addDashedBorder() {
let color = UIColor.red.cgColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 2
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineDashPattern = [6,3]
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
self.layer.addSublayer(shapeLayer)
}
Certainly you can just render your circular UIBezierPath with the selected dash pattern:
class DashedCircleView: UIView {
private var shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = .round
shapeLayer.lineDashPattern = [20, 60]
return shapeLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
}
private extension DashedCircleView {
func configure() {
layer.addSublayer(shapeLayer)
}
func updatePath() {
let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
let radius = min(rect.width, rect.height) / 2
let center = CGPoint(x: rect.midX, y: rect.midY)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
shapeLayer.path = path.cgPath
}
}
That yields:
The problem with that approach is that it’s hard to get the dashed pattern to line up (notice the awkward dashing at the “3 o’clock” position). You can fix that by making sure that the two values of lineDashPattern add up to some number that evenly divides into the circumference of the circle (e.g. 2π × radius):
let circumference: CGFloat = 2 * .pi * radius
let count = 30
let relativeDashLength: CGFloat = 0.25
let dashLength = circumference / CGFloat(count)
shapeLayer.lineDashPattern = [dashLength * relativeDashLength, dashLength * (1 - relativeDashLength)] as [NSNumber]
Alternatively, rather than using lineDashPattern at all, you can instead keep a solid stroke and make the path, itself, as a series of small arcs. That way I can achieve the desired dashed effect, but ensuring it’s evenly split into count little arcs as we rotate from 0 to 2π:
class DashedCircleView: UIView {
private var shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 10
shapeLayer.lineCap = .round
return shapeLayer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
}
private extension DashedCircleView {
func configure() {
layer.addSublayer(shapeLayer)
}
func updatePath() {
let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
let radius = min(rect.width, rect.height) / 2
let center = CGPoint(x: rect.midX, y: rect.midY)
let path = UIBezierPath()
let count = 30
let relativeDashLength: CGFloat = 0.25 // a value between 0 and 1
let increment: CGFloat = .pi * 2 / CGFloat(count)
for i in 0 ..< count {
let startAngle = increment * CGFloat(i)
let endAngle = startAngle + relativeDashLength * increment
path.move(to: CGPoint(x: center.x + radius * cos(startAngle),
y: center.y + radius * sin(startAngle)))
path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
}
shapeLayer.path = path.cgPath
}
}
That yields:
You can use UIBezierPath(ovalIn:) to create a circle path in a square view.
extension UIView {
func addDashedCircle() {
let circleLayer = CAShapeLayer()
circleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
circleLayer.lineWidth = 2.0
circleLayer.strokeColor = UIColor.red.cgColor//border of circle
circleLayer.fillColor = UIColor.white.cgColor//inside the circle
circleLayer.lineJoin = .round
circleLayer.lineDashPattern = [6,3]
layer.addSublayer(circleLayer)
}
}
Set view background color .clear and fill color of the layer .white
class View1: UIViewController {
#IBOutlet weak var circleView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
circleView.backgroundColor = .clear//outside the circle
circleView.addDashedCircle()
}
}
Or using UIBezierPath(arcCenter:radius:startAngle:endAngle:clockwise:)
circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
radius: min(frame.size.height,frame.size.width)/2,
startAngle: 0,
endAngle: .pi * 2,
clockwise: true).cgPath
Draw the path using the circle path variant of UIBezierPath
shapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width * 0.5, y: frame.size.height * 0.5), radius: frame.size.width * 0.5, startAngle: 0, endAngle: .pi * 2, clockwise: true)

Blink Arrow draw with UIBezierPath

I have an UIScrollView which has a long text in it. I want to inform users that It has more content to read. Therefore, I added an arrow with UIBezierPath on bottom of it.
class ArrowView: UIView {
var arrowPath: UIBezierPath!
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
self.drawArrow(from: CGPoint(x: rect.midX, y: rect.minY), to: CGPoint(x: rect.midX, y: rect.maxY),
tailWidth: 10, headWidth: 25, headLength: 20)
//arrowPath.fill()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.darkGray
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func drawArrow(from start: CGPoint, to end: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat){
let length = hypot(end.x - start.x, end.y - start.y)
let tailLength = length - headLength
func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) }
let points: [CGPoint] = [
p(0, tailWidth / 2),
p(tailLength, tailWidth / 2),
p(tailLength, headWidth / 2),
p(length, 0),
p(tailLength, -headWidth / 2),
p(tailLength, -tailWidth / 2),
p(0, -tailWidth / 2)
]
let cosine = (end.x - start.x) / length
let sine = (end.y - start.y) / length
let transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y)
let path = CGMutablePath()
path.addLines(between: points, transform: transform)
path.closeSubpath()
arrowPath = UIBezierPath.init(cgPath: path)
}
}
My question: How can I achieve a blink animation on arrow. Assume that It has a gradient layer from white to blue. It should start with white to blue then blue should seen on start point then white should start to seen on finish point of Arrow and this circle should continue.
On final, this animation should inform users that they can scroll the view.
How can I achieve this?
You can try using CAGradientLayer along with CAAnimation. Add gradient to your view:
override func viewDidAppear(animated: Bool) {
self.gradient = CAGradientLayer()
self.gradient?.frame = self.view.bounds
self.gradient?.colors = [ UIColor.white.cgColor, UIColor.white.cgColor]
self.view.layer.insertSublayer(self.gradient, atIndex: 0)
animateLayer()
}
func animateLayer(){
var fromColors = self.gradient.colors
var toColors: [AnyObject] = [UIColor.blue.cgColor,UIColor.blue.cgColor]
self.gradient.colors = toColors
var animation : CABasicAnimation = CABasicAnimation(keyPath: "colors")
animation.fromValue = fromColors
animation.toValue = toColors
animation.duration = 3.00
animation.isRemovedOnCompletion = true
animation.fillMode = CAMediaTimingFillMode.forwards
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.delegate = self
self.gradient?.addAnimation(animation, forKey:"animateGradient")
}
and to continue gradient animation in cyclic order like:
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
self.toColors = self.fromColors;
self.fromColors = self.gradient?.colors
animateLayer()
}
You could put your arrow inside a UIView object. You could then have the UIView on a timer where it changed the alpha properly. Depending on blinking or fading, nonetheless, you could use UIView Animations to complete your desired animation.
I say a uiview, instead of using the scrollview because you don’t want to hide the scrollview. So you’d put it inside a view in which is only a container for the bezierpath.
I solved it by using CABasicAnimation(). This first add gradient layer to custom UIView then apply mask on it then add animation.
override func draw(_ rect: CGRect) {
// Drawing code
self.drawArrow(from: CGPoint(x: rect.midX, y: rect.minY), to: CGPoint(x: rect.midX, y: rect.maxY),
tailWidth: 10, headWidth: 20, headLength: 15)
//arrowPath.fill()
let startColor = UIColor(red:0.87, green:0.87, blue:0.87, alpha:1.0).cgColor
let finishColor = UIColor(red:0.54, green:0.54, blue:0.57, alpha:1.0).withAlphaComponent(0.5).cgColor
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [startColor,finishColor]
let shapeMask = CAShapeLayer()
shapeMask.path = arrowPath.cgPath
gradient.mask = shapeMask
let animation = CABasicAnimation(keyPath: "colors")
animation.fromValue = [startColor, finishColor]
animation.toValue = [finishColor, startColor]
animation.duration = 2.0
animation.autoreverses = true
animation.repeatCount = Float.infinity
//add the animation to the gradient
gradient.add(animation, forKey: nil)
self.layer.addSublayer(gradient)
}

Corner radius image Swift

I'm trying to make this corner radius image...it's not exactly the same shape of the image..any easy answer instead of trying random numbers of width and height ?
thanks alot
let rectShape = CAShapeLayer()
rectShape.bounds = self.mainImg.frame
rectShape.position = self.mainImg.center
rectShape.path = UIBezierPath(roundedRect: self.mainImg.bounds, byRoundingCorners: [.bottomLeft , .bottomRight ], cornerRadii: CGSize(width: 50, height: 4)).cgPath
You can use QuadCurve to get the design you want.
Here is a Swift #IBDesignable class that lets you specify the image and the "height" of the rounding in Storyboard / Interface Builder:
#IBDesignable
class RoundedBottomImageView: UIView {
var imageView: UIImageView!
#IBInspectable var image: UIImage? {
didSet { self.imageView.image = image }
}
#IBInspectable var roundingValue: CGFloat = 0.0 {
didSet {
self.setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
doMyInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
doMyInit()
}
func doMyInit() {
imageView = UIImageView()
imageView.backgroundColor = UIColor.red
imageView.contentMode = UIViewContentMode.scaleAspectFill
addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
let rect = self.bounds
let y:CGFloat = rect.size.height - roundingValue
let curveTo:CGFloat = rect.size.height + roundingValue
let myBezier = UIBezierPath()
myBezier.move(to: CGPoint(x: 0, y: y))
myBezier.addQuadCurve(to: CGPoint(x: rect.width, y: y), controlPoint: CGPoint(x: rect.width / 2, y: curveTo))
myBezier.addLine(to: CGPoint(x: rect.width, y: 0))
myBezier.addLine(to: CGPoint(x: 0, y: 0))
myBezier.close()
let maskForPath = CAShapeLayer()
maskForPath.path = myBezier.cgPath
layer.mask = maskForPath
}
}
Result with 300 x 200 image view, rounding set to 40:
Edit - (3.5 years later)...
To answer #MiteshDobareeya comment, we can switch the rounded edge from Bottom to Top by transforming the bezier path:
let c = CGAffineTransform(scaleX: 1, y: -1).concatenating(CGAffineTransform(translationX: 0, y: bounds.size.height))
myBezier.apply(c)
It's been quite a while since this answer was originally posted, so a few changes:
subclass UIImageView directly - no need to make it a UIView with an embedded UIImageView
add a Bool roundTop var
if set to False (the default), we round the Bottom
if set to True, we round the Top
re-order and "name" our path points for clarity
So, the basic principle:
We create a UIBezierPath and:
move to pt1
add a line to pt2
add a line to pt3
add a quad-curve to pt4 with controlPoint
close the path
use that path for a CAShapeLayer mask
the result:
If we want to round the Top, after closing the path we can apply apply a scale transform using -1 as the y value to vertically mirror it. Because that transform mirror it at "y-zero" we also apply a translate transform to move it back down into place.
That gives us:
Here's the updated class:
#IBDesignable
class RoundedTopBottomImageView: UIImageView {
#IBInspectable var roundingValue: CGFloat = 0.0 {
didSet {
self.setNeedsLayout()
}
}
#IBInspectable var roundTop: Bool = false {
didSet {
self.setNeedsLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
let r = bounds
let myBezier = UIBezierPath()
let pt1: CGPoint = CGPoint(x: r.minX, y: r.minY)
let pt2: CGPoint = CGPoint(x: r.maxX, y: r.minY)
let pt3: CGPoint = CGPoint(x: r.maxX, y: r.maxY - roundingValue)
let pt4: CGPoint = CGPoint(x: r.minX, y: r.maxY - roundingValue)
let controlPoint: CGPoint = CGPoint(x: r.midX, y: r.maxY + roundingValue)
myBezier.move(to: pt1)
myBezier.addLine(to: pt2)
myBezier.addLine(to: pt3)
myBezier.addQuadCurve(to: pt4, controlPoint: controlPoint)
myBezier.close()
if roundTop {
// if we want to round the Top instead of the bottom,
// flip the path vertically
let c = CGAffineTransform(scaleX: 1, y: -1) //.concatenating(CGAffineTransform(translationX: 0, y: bounds.size.height))
myBezier.apply(c)
}
let maskForPath = CAShapeLayer()
maskForPath.path = myBezier.cgPath
layer.mask = maskForPath
}
}
You can try with UIView extension. as
extension UIView {
func setBottomCurve(){
let offset = CGFloat(self.frame.size.height + self.frame.size.height/1.8)
let bounds = self.bounds
let rectBounds = CGRect(x: bounds.origin.x,
y: bounds.origin.y ,
width: bounds.size.width,
height: bounds.size.height / 2)
let rectPath = UIBezierPath(rect: rectBounds)
let ovalBounds = CGRect(x: bounds.origin.x - offset / 2,
y: bounds.origin.y ,
width: bounds.size.width + offset,
height: bounds.size.height)
let ovalPath = UIBezierPath(ovalIn: ovalBounds)
rectPath.append(ovalPath)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = rectPath.cgPath
self.layer.mask = maskLayer
}
}
& use it in viewWillAppear like methods where you can get actual frame of UIImageView.
Usage:
override func viewWillAppear(_ animated: Bool) {
//use it in viewWillAppear like methods where you can get actual frame of UIImageView
myImageView.setBottomCurve()
}

How to make the background color property of a custom view animatable?

I want to animate my custom view's background color.
My drawing code is very simple. The draw(in:) method is overridden like this:
#IBDesignable
class SquareView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
let strokeWidth = self.width / 8
let path = UIBezierPath()
path.move(to: CGPoint(x: self.width - strokeWidth / 2, y: 0))
path.addLine(to: CGPoint(x: self.width - strokeWidth / 2, y: self.height - strokeWidth / 2))
path.addLine(to: CGPoint(x: 0, y: self.height - strokeWidth / 2))
self.backgroundColor?.darker().setStroke()
path.lineWidth = strokeWidth
path.stroke()
}
}
The darker method just returns a darker version of the color it is called on.
When I set the background to blue, it draws something like this:
I want to animate its background color so that it gradually changes to a red color. This would be the end result:
I first tried:
UIView.animate(withDuration: 1) {
self.square.backgroundColor = .red
}
It just changes the color to red in an instant, without animation.
Then I researched and saw that I need to use CALayers. Therefore, I tried drawing the thing in layers:
#IBDesignable
class SquareViewLayers: UIView {
dynamic var squareColor: UIColor = .blue {
didSet {
setNeedsDisplay()
}
}
func setupView() {
layer.backgroundColor = squareColor.cgColor
let sublayer = CAShapeLayer()
let path = UIBezierPath()
let strokeWidth = self.width / 8
path.move(to: CGPoint(x: self.width - strokeWidth / 2, y: 0))
path.addLine(to: CGPoint(x: self.width - strokeWidth / 2, y: self.height - strokeWidth / 2))
path.addLine(to: CGPoint(x: 0, y: self.height - strokeWidth / 2))
self.tintColor.darker().setStroke()
path.lineWidth = strokeWidth
sublayer.path = path.cgPath
sublayer.strokeColor = squareColor.darker().cgColor
sublayer.lineWidth = strokeWidth
sublayer.backgroundColor = UIColor.clear.cgColor
layer.addSublayer(sublayer)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
But the result is horrible
I used this code to try to animate this:
let anim = CABasicAnimation(keyPath: "squareColor")
anim.fromValue = UIColor.blue
anim.toValue = UIColor.red
anim.duration = 1
square.layer.add(anim, forKey: nil)
Nothing happens though.
I am very confused. What is the correct way to do this?
EDIT:
The darker method is from a cocoa pod called SwiftyColor. This is how it is implemented:
// in an extension of UIColor
public func darker(amount: CGFloat = 0.25) -> UIColor {
return hueColor(withBrightnessAmount: 1 - amount)
}
private func hueColor(withBrightnessAmount amount: CGFloat) -> UIColor {
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return UIColor(hue: hue, saturation: saturation,
brightness: brightness * amount,
alpha: alpha)
}
return self
}
You're on the right track with CABasicAnimation.
The keyPath: in let anim = CABasicAnimation(keyPath: "squareColor") should be backgroundColor.
anim.fromValue and anim.toValue require CGColor values (because you're operating on the CALayer, which uses CGColor). You can use UIColor.blue.cgcolor here.
Pretty sure this animation won't persist the color change for you though, so you might need to change that property manually.
Could you stroke the L-shape with a semi-transparent black instead?
Then you don't have to mess around with redrawing and color calculations, and you can use the basic UIView.animate()
Below the "LShadow" is added onto the SquareView, so you can set the SquareView background color as per usual with UIView.animate()
ViewController.swift
import UIKit
class ViewController: UIViewController {
var squareView: SquareView!
override func viewDidLoad() {
super.viewDidLoad()
squareView = SquareView.init(frame: CGRect(x:100, y:100, width:200, height:200))
self.view.addSubview(squareView)
squareView.backgroundColor = UIColor.blue
UIView.animate(withDuration: 2.0, delay: 1.0, animations: {
self.squareView.backgroundColor = UIColor.red
}, completion:nil)
}
}
SquareView.swift
import UIKit
class SquareView: UIView {
func setupView() {
let shadow = LShadow.init(frame: self.bounds)
self.addSubview(shadow)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
class LShadow: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
let strokeWidth = self.frame.size.width / 8
let path = UIBezierPath()
path.move(to: CGPoint(x: self.frame.size.width - strokeWidth / 2, y: 0))
path.addLine(to: CGPoint(x: self.frame.size.width - strokeWidth / 2, y: self.frame.size.height - strokeWidth / 2))
path.addLine(to: CGPoint(x: 0, y: self.frame.size.height - strokeWidth / 2))
UIColor.init(white: 0, alpha: 0.5).setStroke()
path.lineWidth = strokeWidth
path.stroke()
}
}
Using CAKeyframeAnimation you need to animate backgroundColor property:
class SquareView: UIView
{
let sublayer = CAShapeLayer()
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
let frame = self.frame
let strokeWidth = self.frame.width / 8
sublayer.frame = self.bounds
let path = UIBezierPath()
path.move(to: CGPoint(x: frame.width - strokeWidth / 2 , y: 0))
path.addLine(to: CGPoint(x: frame.width - strokeWidth / 2, y: frame.height - strokeWidth / 2))
path.addLine(to: CGPoint(x: 0, y: frame.height - strokeWidth / 2))
path.addLine(to: CGPoint(x: 0 , y: 0))
path.lineWidth = strokeWidth
sublayer.path = path.cgPath
sublayer.fillColor = UIColor.blue.cgColor
sublayer.lineWidth = strokeWidth
sublayer.backgroundColor = UIColor.blue.cgColor
layer.addSublayer(sublayer)
}
//Action
func animateIt()
{
let animateToColor = UIColor(cgColor: sublayer.backgroundColor!).darker().cgColor
animateColorChange(mLayer: self.sublayer, colors: [sublayer.backgroundColor!, animateToColor], duration: 1)
}
func animateColorChange(mLayer:CALayer ,colors:[CGColor], duration:CFTimeInterval)
{
let animation = CAKeyframeAnimation(keyPath: "backgroundColor")
CATransaction.begin()
animation.keyTimes = [0.2, 0.5, 0.7, 1]
animation.values = colors
animation.calculationMode = kCAAnimationPaced
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.repeatCount = 0
animation.duration = duration
mLayer.add(animation, forKey: nil)
CATransaction.commit()
}
}
Note: I have edited the answer so that the shape will always fit the parent view added from storyboard
I had an implementation of changing the background color of view with animation and did some tweak in the source code to add inverted L shape using CAShapeLayer. I achieved the required animation. here is the sample of the view.
class SquareView: UIView, CAAnimationDelegate {
fileprivate func setup() {
self.layer.addSublayer(self.sublayer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup
}
let sublayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
let strokeWidth = self.bounds.width / 8
var frame = self.bounds
frame.size.width -= strokeWidth
frame.size.height -= strokeWidth
self.sublayer.path = UIBezierPath(rect: frame).cgPath
}
var color : UIColor = UIColor.clear {
willSet {
self.sublayer.fillColor = newValue.cgColor
self.backgroundColor = newValue.darker()
}
}
func animation(color: UIColor, duration: CFTimeInterval = 1.0) {
let animation = CABasicAnimation()
animation.keyPath = "backgroundColor"
animation.fillMode = kCAFillModeForwards
animation.duration = duration
animation.repeatCount = 1
animation.autoreverses = false
animation.fromValue = self.backgroundColor?.cgColor
animation.toValue = color.darker().cgColor
animation.delegate = self;
let shapeAnimation = CABasicAnimation()
shapeAnimation.keyPath = "fillColor"
shapeAnimation.fillMode = kCAFillModeForwards
shapeAnimation.duration = duration
shapeAnimation.repeatCount = 1
shapeAnimation.autoreverses = false
shapeAnimation.fromValue = self.sublayer.fillColor
shapeAnimation.toValue = color.cgColor
shapeAnimation.delegate = self;
self.layer.add(animation, forKey: "kAnimation")
self.sublayer.add(shapeAnimation, forKey: "kAnimation")
self.color = color
}
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
self.layer.removeAnimation(forKey: "kAnimation")
self.sublayer.removeAnimation(forKey: "kAnimation")
}
}
You can use the method animation(color: duration:) to change the color with animation on required animation duration.
Example
let view = SquareView(frame: CGRect(x: 10, y: 100, width: 200, height: 300))
view.color = UIColor.blue
view.animation(color: UIColor.red)
Here is the result
We have in the code below, two different CAShapeLayer, foreground and background. Background is a rectangle path drawn to the extent where inverted L actually starts. And L is the path created with simple UIBezierPath geometry. I animate the change to fillColor for each layer after color is set.
class SquareViewLayers: UIView, CAAnimationDelegate {
var color: UIColor = UIColor.blue {
didSet {
animate(layer: backgroundLayer,
from: oldValue,
to: color)
animate(layer: foregroundLayer,
from: oldValue.darker(),
to: color.darker())
}
}
let backgroundLayer = CAShapeLayer()
let foregroundLayer = CAShapeLayer()
func setupView() {
foregroundLayer.frame = frame
layer.addSublayer(foregroundLayer)
backgroundLayer.frame = frame
layer.addSublayer(backgroundLayer)
let strokeWidth = width / 8
let backgroundPathRect = CGRect(origin: .zero, size: CGSize(width: width - strokeWidth,
height: height - strokeWidth))
let backgroundPath = UIBezierPath(rect: backgroundPathRect)
backgroundLayer.fillColor = color.cgColor
backgroundLayer.path = backgroundPath.cgPath
let foregroundPath = UIBezierPath()
foregroundPath.move(to: CGPoint(x: backgroundPathRect.width,
y: 0))
foregroundPath.addLine(to: CGPoint(x: width,
y: 0))
foregroundPath.addLine(to: CGPoint(x: width, y: height))
foregroundPath.addLine(to: CGPoint(x: 0,
y: height))
foregroundPath.addLine(to: CGPoint(x: 0,
y: backgroundPathRect.height))
foregroundPath.addLine(to: CGPoint(x: backgroundPathRect.width,
y: backgroundPathRect.height))
foregroundPath.addLine(to: CGPoint(x: backgroundPathRect.width,
y: 0))
foregroundPath.close()
foregroundLayer.path = foregroundPath.cgPath
foregroundLayer.fillColor = color.darker().cgColor
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func animate(layer: CAShapeLayer,
from: UIColor,
to: UIColor) {
let fillColorAnimation = CABasicAnimation(keyPath: "fillColor")
fillColorAnimation.fromValue = from.cgColor
layer.fillColor = to.cgColor
fillColorAnimation.duration = 1.0
layer.add(fillColorAnimation,
forKey: nil)
}
}
And here is the result,
Objective-C
view.backgroundColor = [UIColor whiteColor].CGColor;
[UIView animateWithDuration:2.0 animations:^{
view.layer.backgroundColor = [UIColor greenColor].CGColor;
} completion:NULL];
Swift
view.backgroundColor = UIColor.white.cgColor
UIView.animate(withDuration: 2.0) {
view.backgroundColor = UIColor.green.cgColor
}

Resources