iOS,如何连续动画一行 "running"("marching ants"效果)?

标签 ios swift animation

我必须承认我不知道如何在 iOS 中执行此操作 -

下面是一些制作漂亮虚线的代码:

enter image description here

现在,我希望这条线向上“运行”:

因此,每隔一秒它就会向上移动 itemLength * 2.0

当然,它会从上到下环绕。

因此,DottedVertical 应该完全独立完成此操作。

真的,你如何在 iOS 中做到这一点?

如果解决方案是通用的并且会“滚动”任何我认为的层或绘制的东西,那就太好了。

在游戏引擎中,它很简单,您只需为纹理的偏移设置动画。您能否在 iOS 中偏移图层或其他内容?

什么是最好的方法?

我猜你会想要使用 GPU(图层动画对吗?)以避免融化 cpu。

@IBDesignable class DottedVertical: UIView {

    @IBInspectable var dotColor: UIColor = UIColor.faveColor

    override func draw(_ rect: CGRect) {

        // say you want 8 dots, with perfect fenceposting:
        let totalCount = 8 + 8 - 1
        let fullHeight = bounds.size.height
        let width = bounds.size.width
        let itemLength = fullHeight / CGFloat(totalCount)
        let beginFromTop = !lowerHalfOnly ? 0.0 : (fullHeight * 8.0 / 15.0)
        let top = CGPoint(x: width/2, y: beginFromTop)
        let bottom = CGPoint(x: width/2, y: fullHeight)

        let path = UIBezierPath()
        path.move(to: top)
        path.addLine(to: bottom)
        path.lineWidth = width
        let dashes: [CGFloat] = [itemLength, itemLength]
        path.setLineDash(dashes, count: dashes.count, phase: 0)
        dotColor.setStroke()
        path.stroke()
}

(奖励 - 如果屏幕上有一些这样的内容,它们当然必须同步。需要有一个“同步”调用来启动正在运行的动画,这样您就可以开始一次通知或其他消息。)

最佳答案

不想回答我自己的问题,这里有一个基于上述男士建议的复制粘贴解决方案!

好样的!效果极佳...

@IBDesignable class DottedVertical: UIView {

    @IBInspectable var dotColor: UIColor = sfBlack6 { didSet {setup()} }

    override func layoutSubviews() { setup() }

    var s:CAShapeLayer? = nil

    func setup() {
        // say you want 8 dots, with perfect fenceposting:
        - calculate exactly as in the example in the question above -

        // marching ants...

        if (s == nil) {
            s = CAShapeLayer()
            self.layer.addSublayer(s!)
        }

        s!.strokeColor = dotColor.cgColor
        s!.fillColor = backgroundColor?.cgColor
        s!.lineWidth = width
        let ns = NSNumber(value: Double(itemLength))
        s!.lineDashPattern = [ns, ns]

        let path = CGMutablePath()
        path.addLines(between: [top, bottom])
        s!.path = path

        let anim = CABasicAnimation(keyPath: "lineDashPhase")
        anim.fromValue = 0
        anim.toValue = ns + ns
        anim.duration = 1.75 // seconds
        anim.repeatCount = Float.greatestFiniteMagnitude

        s!.add(anim, forKey: nil)

        self.layer.addSublayer(s!)
    }
}

关于iOS,如何连续动画一行 "running"("marching ants"效果)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936819/

相关文章:

iOS:与 UIButton 的 UIControlEventTouchUpOutside 事件的行为不一致

objective-c - 托管对象上下文仅保存托管对象循环的最后一条记录

ios - 实现 MVC 模式

ios - 快速 if 语句检查字符串不正确

jQuery 动画回调

objective-c - UITableViewController 在网络请求完成之前执行延迟功能

ios - 如何在一个 View Controller 中拥有多个 Collection View ?

ios - Swift nil 检查性能

animation - Threejs Mixer 未更新为 `setTime`

css - 动画信标 CSS