创建圆形动画的正确方法是什么?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建圆形动画的正确方法是什么?相关的知识,希望对你有一定的参考价值。

我刚看到这个图像,对我来说很有趣,如何在Swift中创建这种类型的动画:

enter image description here

所以,我有很多灰色的圆圈,当我设置角度时,例如45度,它会将这些灰色的牙齿填充到0..45度内的蓝色。

您可以向我解释正确的方法,或者您可以显示不同的片段(这会很棒)。后来我会搜索或阅读它。

提前致谢!

答案

如果您只需要单独的“牙齿”来改变颜色,而不是使用牙齿作为固体填充的面具,您可以使用Core Graphics而不是Core Animation(尽管通常首选Core Animation)。所以为了做到这一点,我们应该做以下事情:

  1. 子类UIView插入我们的绘图代码
  2. 创建一个包含在UIBezierPath中的路径对象数组
  3. 设置计时器以更新进度值和setNeedsDisplay
  4. drawRect:中,绘制路径并根据进度为每个路径分配填充

首先,让我们在这个UIView子类中定义我们将要使用的变量。

class TeethLoaderView : UIView {

    let numberOfTeeth = UInt(60) // Number of teeth to render
    let teethSize = CGSize(width:8, height:45) // The size of each individual tooth
    let animationDuration = NSTimeInterval(5.0) // The duration of the animation

    let highlightColor = UIColor(red: 29.0/255.0, green: 175.0/255.0, blue: 255.0/255.0, alpha: 1) // The color of a tooth when it's 'highlighted'
    let inactiveColor = UIColor(red: 233.0/255.0, green: 235.0/255.0, blue: 236.0/255.0, alpha: 1) // The color of a tooth when it isn't 'hightlighted'

    var progress = NSTimeInterval(0.0) // The progress of the loader
    var paths = [UIBezierPath]() // The array containing the UIBezier paths
    var displayLink = CADisplayLink() // The display link to update the progress
    var teethHighlighted = UInt(0) // Number of teeth highlighted

    ...

现在让我们添加一个函数来创建我们的路径。

func getPaths(size:CGSize, teethCount:UInt, teethSize:CGSize, radius:CGFloat) -> [UIBezierPath] {

    let halfHeight = size.height*0.5;
    let halfWidth = size.width*0.5;
    let deltaAngle = CGFloat(2*M_PI)/CGFloat(teethCount); // The change in angle between paths

    // Create the template path of a single shape.
    let p = CGPathCreateWithRect(CGRectMake(-teethSize.width*0.5, radius, teethSize.width, teethSize.height), nil);

    var pathArray = [UIBezierPath]()
    for i in 0..<teethCount { // Copy, translate and rotate shapes around

        let translate = CGAffineTransformMakeTranslation(halfWidth, halfHeight);
        var rotate = CGAffineTransformRotate(translate, deltaAngle*CGFloat(i))
        let pathCopy = CGPathCreateCopyByTransformingPath(p, &rotate)!

        pathArray.append(UIBezierPath(CGPath: pathCopy)) // Populate the array
    }

    return pathArray
}

这很简单。我们只需为单个“牙齿”创建一条路径,然后将此路径复制到我们需要的牙齿数量,为每个牙齿平移和旋转路径。

接下来我们要设置我们的视图。我要去定时器的CADisplayLink,以便动画在所有设备上以相同的速度运行。

override init(frame: CGRect) {
    super.init(frame: frame)
    commonSetup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonSetup()
}

private func commonSetup() {
    self.backgroundColor = UIColor.whiteColor()
    paths = getPaths(frame.size, teethCount: numberOfTeeth, teethSize: teethSize, radius: ((frame.width*0.5)-teethSize.height))

    displayLink = CADisplayLink(target: self, selector: #selector(displayLinkDidFire));
    displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}

在这里,我们只设置背景颜色,以及设置我们的计时器并初始化我们将要使用的路径。接下来我们要设置一个函数来在CADisplayLink触发时更改视图的进度。

func displayLinkDidFire() {

    progress += displayLink.duration/animationDuration

    if (progress > 1) {
        progress -= 1
    }

    let t = teethHighlighted

    teethHighlighted = UInt(round(progress*NSTimeInterval(numberOfTeeth))) // Calculate the number of teeth to highlight

    if (t != teethHighlighted) { // Only call setNeedsDisplay if the teethHighlighted changed
        setNeedsDisplay()
    }
}

这里没什么复杂的,我们只是更新进度和teethHighlighted并调用setNeedsDisplay()重绘视图,如果teethHighlighted改变了。

最后,我们想绘制视图。

override func drawRect(rect: CGRect) {

    let ctx = UIGraphicsGetCurrentContext()

    CGContextScaleCTM(ctx, -1, -1) // Flip the context to the correct orientation
    CGContextTranslateCTM(ctx, -rect.size.width, -rect.size.height)

    for (index, path) in paths.enumerate() { // Draw each 'tooth'

        CGContextAddPath(ctx, path.CGPath);

        let fillColor = (UInt(index) <= teethHighlighted) ? highlightColor:inactiveColor;

        CGContextSetFillColorWithColor(ctx, fillColor.CGColor)
        CGContextFillPath(ctx)
    }
}

如果你想沿着核心动画路径走下去,那就是I adapted this code into a Core Animation layer


最后结果

enter image description here


完整项目:https://github.com/hamishknight/Circle-Loader

另一答案

好吧,本着“大或回家”的精神(因为我实际上有一些乐趣),我创建了一个核心动画版本of my Core Graphics answer。它的代码相当少,动画更流畅,所以我更喜欢使用它。

首先,让我们再次对UIView进行子类化(这不是绝对必要的,但在单个视图中包含所有内容很好)并定义我们的变量:

class TeethLoaderViewCA : UIView {

    let numberOfTeeth = UInt(60) // Number of teetch to render
    let teethSize = CGSize(width:8, height:45) // The size of each individual tooth
    let animationDuration = NSTimeInterval(5.0) // The duration of the animation

    let highlightColor = UIColor(red: 29.0/255.0, green: 175.0/255.0, blue: 255.0/255.0, alpha: 1) // The color of a tooth when it's 'highlighted'
    let inactiveColor = UIColor(red: 233.0/255.0, green: 235.0/255.0, blue: 236.0/255.0, alpha: 1) // The color of a tooth when it isn't 'hightlighted'

    let shapeLayer = CAShapeLayer() // The teeth shape layer
    let drawLayer = CAShapeLayer() // The arc fill layer

    let anim = CABasicAnimation(keyPath: "strokeEnd") // The stroke animation

    ...

这与Core Graphics版本大致相同,但有几个Core Animation对象且没有时序逻辑。接下来,我们可以复制我们在其他版本中创建的getPaths函数,除了一些调整。

func getPathMask(size:CGSize, teethCount:UInt, teethSize:CGSize, radius:CGFloat) -> CGPathRef? {

    let halfHeight = size.height*0.5
    let halfWidth = size.width*0.5
    let deltaAngle = CGFloat(2*M_PI)/CGFloat(teethCount); // The change in angle between paths

    // Create the template path of a single shape.
    let p = CGPathCreateWithRect(CGRectMake(-teethSize.width*0.5, radius, teethSize.width, teethSize.height), nil)

    let returnPath = CGPathCreateMutable()

    for i in 0..<teethCount { // Copy, translate and rotate shapes around
        let translate = CGAffineTransformMakeTranslation(halfWidth, halfHeight)
        var rotate = CGAffineTransformRotate(translate, deltaAngle*CGFloat(i))
        CGPathAddPath(returnPath, &rotate, p)
    }

    return CGPathCreateCopy(returnPath)
}

这次,所有路径都被分组为一个大路径,函数返回该路径。

最后,我们只需要创建图层对象并设置动画。

private func commonSetup() {

    // set your background color
    self.backgroundColor = UIColor.whiteColor()

    // Get the group of paths we created.
    shapeLayer.path = getPathMask(frame.size, teethCount: numberOfTeeth, teethSize: teethSize, radius: ((frame.width*0.5)-teethSize.height))

    let halfWidth = frame.size.width*0.5
    let halfHeight = frame.size.height*0.5
    let halfDeltaAngle = CGFloat(M_PI/Double(numberOfTeeth))

    // Creates an arc path, with a given offset to allow it to be presented nicely
    drawLayer.path = UIBezierPath(arcCenter: CGPointMake(halfWidth, halfHeight), radius: halfWidth, startAngle: CGFloat(-M_PI_2)-halfDeltaAngle, endAngle: CGFloat(M_PI*1.5)+halfDeltaAngle, clockwise: true).CGPath
    drawLayer.frame = frame
    drawLayer.fillColor = inactiveColor.CGColor
    drawLayer.strokeColor = highlightColor.CGColor
    drawLayer.strokeEnd = 0
    drawLayer.lineWidth = halfWidth
    drawLayer.mask = shapeLayer
    layer.addSublayer(drawLayer)

    // Optional, but looks nice
    anim.timingFunction = CAMediaTimingFun

以上是关于创建圆形动画的正确方法是什么?的主要内容,如果未能解决你的问题,请参考以下文章

创建圆形ImageView的最佳方法是什么? [关闭]

具有突出显示不透明度和动画的圆形 UIButton

动画圆形 UIBezierPath 不四舍五入的笔划

圆形到矩形的变换动画

在 Flutter 动画中更新动画值的正确方法是啥?

使用带有actionscript 3 Flash cs6的矩形或线条创建2D重复模式