Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CALayer та його підкласи. Приклади та використання by Dmytro Cheverda

CALayer та його підкласи. Приклади та використання by Dmytro Cheverda

CALayer та його підкласи. Приклади та використання by Dmytro Cheverda

GDG Ternopil

October 20, 2015
Tweet

More Decks by GDG Ternopil

Other Decks in Programming

Transcript

  1. CALayer • All views have a backing layer property: ◦

    view.layer • Base layer class • Manage and animate visual content • Layers have properties ◦ Most automatically animated • Can add additional animations
  2. CALayer • Many subclasses of CALayer • Default layer class

    CALayer, but you can change: ◦ + (Class)layerClass; • Layers can have sublayers • Better performance than UIView (renders on GPU)
  3. Basic properties • Rounded corners: ◦ cornerRadius • Borders: ◦

    borderWidth, borderColor • Shadows: ◦ shadowOpacity, shadowRadius, shadowOffset, shadowColor, shadowPath • Mask: ◦ mask, masksToBounds • Contents: ◦ contents, contentsGravity
  4. Subclasses • CAScrollLayer • CAShapeLayer • CATextLayer • CAGradientLayer •

    CAReplicatorLayer • CATiledLayer • CATransformLayer • CAEmitterLayer • CAEAGLLayer • AVPlayerLayer
  5. • Draw using scalable vector paths • Faster than: ◦

    layer.contents = UIImage(named: … ) • No pixelation, no clipping, and preserves aspect ratio • Can change line thickness and dashing, how lines end or join other lines, and line and fill color • Great animation support • Use UIBezierPath for easy CGPath creation CAShapeLayer
  6. CAShapeLayer • Path: ◦ path • Fill: ◦ fillColor, fillRule

    • Stroke: ◦ strokeColor, strokeStart, strokeEnd • Line tweaks: ◦ lineCap, lineDashPattern, lineDashPhase, lineJoin lineWidth, miterLimit
  7. CAShapeLayer • Creation: let sl = CAShapeLayer() sl.frame = shapeView.frame

    sl.fillColor = UIColor.greenColor().CGColor sl.strokeColor = UIColor.redColor().CGColor sl.strokeStart = 0.02 sl.strokeEnd = 0.98 sl.lineJoin = kCALineJoinBevel sl.lineWidth = 10 sl.lineDashPhase = 50 sl.lineCap = kCALineCapRound sl.lineDashPattern = [25, 15]
  8. CAShapeLayer • Adding morphing animation: let newPath = UIBezierPath(ovalInRect: CGRectMake(20,

    20, 400, 400)).CGPath let anim = CABasicAnimation(keyPath: "path") anim.beginTime = CACurrentMediaTime() + CFTimeInterval(5.0) anim.duration = 4.0 anim.toValue = newPath anim.removedOnCompletion = false anim.fillMode = kCAFillModeForwards shapeLayer.addAnimation(anim, forKey: nil)
  9. CATextLayer • Render plain text or attributed strings • Similar

    capabilities as UILabel • Can change text, font, size, color, wrapping, alignment and truncation
  10. CATextLayer • Creation: let tl = CATextLayer() tl.frame = textView.frame

    tl.string = "CATextLayer" tl.wrapped = true tl.fontSize = 32 tl.alignmentMode = kCAAlignmentJustified tl.truncationMode = kCATruncationEnd tl.foregroundColor = UIColor.darkGrayColor().CGColor
  11. CATextLayer • Font size animation: let anim = CABasicAnimation(keyPath: "fontSize")

    anim.duration = 2.0 anim.toValue = 32 anim.fromValue = 12 textLayer.addAnimation(anim, forKey: nil)
  12. CAReplicatorLayer • Duplicate a source layer • Creates specified number

    of copies • Applies a transform to each copy • Can delay drawing of each copy • Can preserve depth • Configure instance: ◦ instanceCount, instanceTransform, instanceDelay
  13. CAReplicatorLayer • Creation: let dotsCount: Int = 16 let duration:

    CFTimeInterval = 1.5 let angle = CGFloat(2 * M_PI) / CGFloat(dotsCount) let sideLength: CGFloat = 300 let r = CAReplicatorLayer() r.frame = CGRectMake(0, 0, sideLength, sideLength) r.position = replicatorView.center r.instanceCount = dotsCount r.instanceTransform = CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0) r.instanceDelay = duration / Double(dotsCount)
  14. CAReplicatorLayer • Creation of dot layer: let dot = CALayer()

    dot.frame = CGRectMake(0, 0, sideLength * 0.1, sideLength * 0.15) dot.backgroundColor = UIColor.blueColor().CGColor dot.position = CGPointMake(sideLength / 2.0, sideLength * 0.1) dot.cornerRadius = sideLength * 0.05 // fix dots original size at animation beginning dot.transform = CATransform3DMakeScale(0.01, 0.01, 0.01) r.addSublayer(dot)
  15. CAReplicatorLayer • Adding shrink animation: let shrink = CABasicAnimation(keyPath: "transform.scale")

    shrink.fromValue = 1.0 shrink.toValue = 0.1 shrink.duration = duration shrink.repeatCount = Float.infinity dot.addAnimation(shrink, forKey: nil)
  16. CAReplicatorLayer • Adding fade animation: let fade = CABasicAnimation(keyPath: "opacity")

    fade.fromValue = 1.0 fade.toValue = 0.1 fade.duration = duration fade.repeatCount = Float.infinity dot.addAnimation(fade, forKey: nil)
  17. CAReplicatorLayer • Adding color animation: let color = CABasicAnimation(keyPath: "backgroundColor")

    color.fromValue = UIColor.blueColor().CGColor color.toValue = UIColor.redColor().CGColor color.duration = duration color.repeatCount = Float.infinity dot.addAnimation(color, forKey: nil)
  18. CAReplicatorLayer • Dot progress creation: let dotsCount: Int = 5

    let duration: CFTimeInterval = 0.6 let dotSize: CGSize = CGSizeMake(50, 50) let dotSpacing: CGFloat = 60 let r = CAReplicatorLayer() r.frame = view.frame r.position = view.center r.instanceCount = dotsCount r.instanceDelay = duration / Double(dotsCount) r.instanceTransform = CATransform3DMakeTranslation(dotSpacing, 0, 1.0)
  19. CAReplicatorLayer • Adding shrink animation: let shrink = CABasicAnimation(keyPath: "transform.scale")

    shrink.fromValue = 1.0 shrink.toValue = 0.5 shrink.duration = duration shrink.autoreverses = true shrink.repeatCount = Float.infinity shrink.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) dot.addAnimation(shrink, forKey: nil)
  20. CAReplicatorLayer • Adding fade animation: let fade = CABasicAnimation(keyPath: "backgroundColor")

    fade.fromValue = UIColor.blueColor().CGColor fade.toValue = UIColor(red: 0.0, green: 0.0, blue: 0.7, alpha: 1.0). CGColor fade.duration = duration fade.autoreverses = true fade.repeatCount = Float.infinity dot.addAnimation(fade, forKey: nil)
  21. CAGradientLayer • Apply color gradient over the background • Faster

    than using CoreGraphics • Can change color, locations, start/end points
  22. CAGradientLayer • Basic setup let gradientLayer = CAGradientLayer() gradientLayer.frame =

    frame gradientLayer.colors = [ UIColor.redColor().CGColor, UIColor.greenColor().CGColor, UIColor.blueColor().CGColor ] gradientView.layer.addSublayer(gradientLayer)
  23. CAGradientLayer • Adding gradient to UILabel as a mask let

    label = UILabel(frame: gradientView.frame) gradientView.addSubview(label) label.text = "Okay - now let’s mask the gradient with the label… “What?” some of you are certainly saying just now. Well - just give it a try, will you?" label.numberOfLines = 0 label.font = UIFont.systemFontOfSize(60) gradientLayer.mask = label.layer
  24. CAEmitterLayer • Render animated particles • Particles are instances of

    CAEmitterCell • Draw particles above backgroundColor and border • Can change render mode and emitter position, shape, size, spin, velocity, birth rate, and lifetime • Can preserve depth to render in 3D • Can change cell contents, color, speed of color change, scale, emission latitude/longitude, initial velocity, acceleration, birth date, lifetime, magnification/minification filters
  25. CAEmitterLayer • Create basic layer let e = CAEmitterLayer() e.frame

    = view.frame e.emitterSize = CGSizeMake(450, 20) e.emitterPosition = CGPointMake(200, -50) e.emitterZPosition = 1 e.emitterShape = kCAEmitterLayerLine e.renderMode = kCAEmitterLayerOldestLast
  26. CAEmitterLayer • Create emitter cell let cell = CAEmitterCell() cell.scale

    = 1.0 cell.lifetime = 7.0 cell.birthRate = 50 cell.yAcceleration = 50 cell.xAcceleration = 5 cell.contents = UIImage(named: "star")?.CGImage cell.spin = 0.5 e.emitterCells = [cell]
  27. CATiledLayer • Asynchronously draw layer content in tiles • Can

    be used to asynchronously draw large image • Can change tile size, resolution, and fade duration
  28. CATransformLayer • Draw 3D structures • Unlike CAlayers only its

    sublayers are rendered • Does not flatten its sublayers • Each sublayer has its own opacity • Transform is applied to sublayers • Transform ignores changes to rendered layer properties • Cannot directly hit-test ◦ but can hit-test sublayers
  29. CAScrollLayer • Display portion of a scrollable layer • Can

    lock horizontal and/or vertical • UIScrollView doesn’t use it • Cannot directly react to touch or bounds check • Use UIScrollView when scrolling is touch-based ◦ Instead it directly changes its layer’s bounds • Use CATiledLayer when scrolling large images
  30. AVPlayerLayer • Display an AVPlayer • Can change player and

    videoGravity, and videoRect • AVPlayer includes play(), pause(), rate and seek • AVPlayerItem has many useful properties and callbacks
  31. CAMetalLayer • Manages a pool of Metal textures • Use

    this class as the backing layer for a view • Demo: http://flexmonkey.blogspot.com/2015/03/swift-metal-four-million- particles-on.html
  32. Notes • Implicit & explicit animations • Use: ◦ CGPath,

    CGImage, CGColor • Instead of: ◦ UIBezierPath, UIImage, UIColor • shouldRasterize, drawsAsynchronously • Use CATransform3D instead of CATransform2D • geometryFlipped
  33. Conclusion • Layers are an easy and efficient way to

    get cool effects into your app • Layers have great support for animation • CALayer are often the foundation for custom iOS controls • AsyncDisplayKit takes advantage of CALayer to update UI in background Playground:https://docs.google. com/presentation/d/1j5vK14VfotpUfmxzpEJO8CpFmDora1gW50Nkfs9o9hQ/edit#slide=id.p Presenation:https://github.com/dimacheverda/CALayerPlayground