2016-09-12 19 views
1

我正在使用drawRect绘制一个非常简单的形状(下图中为深蓝色)。使用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) 

我如何可以动画的蓝色部分由左到右,同时保持图形的灰度“MAX”部分总是可见的?

回答

1

drawRect正在产生静止图像。为了得到你说的动画约我提出以下建议:

  1. 使用CoreAnimation制作动画
  2. 使用UIBezierPath做出形状,你需要
  3. 使用的CALayer的面具所需形状
  4. 内动画

下面是游乐场的示例代码:

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") 
+0

@SVGred - 哇,太棒了!大多数情况下,这正是我需要的!我需要稍微修改一下,但这是关于我的。 随着我最初的图形实现,我用覆盖func drawRect(rect:CGRect)分类UIView。我不需要为您的版本重写drawRect吗? 另外 - 你能解释最后一行吗? (layerTwo.addAnimation) 我编辑你的文章swift 2.3语法以及。在我的最后播放很棒! – Joe

+0

@SVGreg与正在使用的多个Swift版本,这将是很好的提及你在哪写你的答案。 – Dravidian

+1

@Joe:drawRect仅用于在视图内绘制自定义内容。答案是 - 不 - 你不需要重写* drawRect *来使用我的代码。 addAnimation实际上是运行你需要的动画。您可以将其自定义为您喜欢的任何动画。 – SVGreg

0

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

我不认为它是足够有效的在drawRect函数中实现动画。

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

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

+0

“在你的代码中,我只看到你画的图形一次,为什么不先绘制灰色部分,然后绘制蓝色部分。“ - 这是计划,只要我想出一种方法来制作动画,或者可能使蓝色图层的蒙版动画化。感谢关于这些框架的建议,但我想保持这一切都没有任何第三方本土。 – Joe