1

我正在使用 drawRect 绘制一个非常简单的形状(下图中的深蓝色)。

CGContextDrawPath 我希望这个动画从左到右,以便它增长。这里需要注意的是,我需要有一个灰色的“最大”背景,如图像的顶部所示。

现在,我通过覆盖一个白色视图来模拟这个动画,然后设置它的大小,使它看起来像蓝色的动画向右。虽然这有效......我需要背景灰色形状始终存在。使用我的叠加白色视图,这不起作用。

这是绘制“当前代码”版本的代码:

    let context = UIGraphicsGetCurrentContext()
    CGContextMoveToPoint(context, 0, self.bounds.height - 6)
    CGContextAddLineToPoint(context, self.bounds.width, 0)
    CGContextAddLineToPoint(context, self.bounds.width, self.bounds.height)
    CGContextAddLineToPoint(context, 0, self.bounds.height)
    CGContextSetFillColorWithColor(context,UIColor(red: 37/255, green: 88/255, blue: 120/255, alpha: 1.0).CGColor)
    CGContextDrawPath(context, CGPathDrawingMode.Fill)

如何从左到右为蓝色部分设置动画,同时保持图形的灰色“最大”部分始终可见?

4

2 回答 2

1

drawRect 正在生成静止图像。要获得您所说的动画,我建议以下内容:

  1. 使用 CoreAnimation 制作动画
  2. 使用 UIBezierPath 制作您需要的形状
  3. 使用 CALayer 的蒙版在所需形状内设置动画

这是 Playground 的示例代码:

import UIKit
import QuartzCore
import XCPlayground

let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
XCPlaygroundPage.currentPage.liveView = view

let maskPath = UIBezierPath()

maskPath.moveToPoint(CGPoint(x: 10, y: 30))
maskPath.addLineToPoint(CGPoint(x: 10, y: 25))
maskPath.addLineToPoint(CGPoint(x: 100, y: 10))
maskPath.addLineToPoint(CGPoint(x: 100, y: 30))
maskPath.closePath()

let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.whiteColor().CGColor

let rectToAnimateFrom = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 97, height: 40))
let rectToAnimateTo = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: 40))

let layerOne = CAShapeLayer()
layerOne.path = maskPath.CGPath
layerOne.fillColor = UIColor.grayColor().CGColor

let layerTwo = CAShapeLayer()
layerTwo.mask = maskLayer
layerTwo.fillColor = UIColor.greenColor().CGColor

view.layer.addSublayer(layerOne)
view.layer.addSublayer(layerTwo)

let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = rectToAnimateFrom.CGPath
animation.toValue = rectToAnimateTo.CGPath
animation.duration = 1
animation.repeatCount = 1000
animation.autoreverses = true

layerTwo.addAnimation(animation, forKey: "Nice animation")
于 2016-09-12T17:08:35.720 回答
0

在您的代码中,我只看到您绘制了一次图形,为什么不先绘制灰色部分,然后再绘制蓝色部分。

我认为在 drawRect 函数中实现动画效率不够高。

你可以看看 Facebook 的Shimmer Example,它模拟了 iPhone 解锁动画的效果。它使用遮罩层。这个想法也可以在你的例子中起作用。

此外,Facebook 的pop 框架可以简化您的工作。

于 2016-09-12T16:35:49.847 回答