我是新手,对我遇到的这个问题感到沮丧。
我要做的非常简单:在屏幕中央画一条直线并为其制作动画。听起来很简单吧?是啊..这就是我现在所拥有的。
import UIKit
class Drawings: UIView {
override func drawRect(rect: CGRect) {
let screensize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screensize.width
let screenHeight = screensize.height
//context
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 7.0)
CGContextSetStrokeColorWithColor(context, UIColor.whiteColor().CGColor)
//path
CGContextMoveToPoint(context, screenWidth, screenHeight * 0.5)
CGContextAddLineToPoint(context, screenWidth * 0.5, screenHeight * 0.5)
CGContextSetLineCap(context, CGLineCap.Round)
//draw
CGContextStrokePath(context)
}
}
我问的原因是我发现我无法为其设置动画,因为它在drawRect函数中。真的吗?需要你们的一些解释。谢谢!
答案 0 :(得分:5)
你不应该像这样在drawRect
中绘制形状,特别是如果你要进行动画制作。
相反,制作一个CAShapeLayer,您可以使用Core Animation为其设置动画。
// Create the path using UIBezierPath.
// Position can start at 0,0 because we'll move it using the layer
let linePath = UIBezierPath()
linePath.moveToPoint(CGPoint(x: 0, y: 0))
linePath.addLineToPoint(CGPoint(x: CGRectGetMidX(frame), y: 0))
// Create the shape layer that will draw the path
let lineLayer = CAShapeLayer()
// set the bounds to the size of the path.
// You could also set to the size of your view,
// but if i know the size of my shape ahead of time,
// I like to set it to be the same.
lineLayer.bounds = linePath.bounds
// give it the same position as our view's layer.
// layers have an anchor point of 0.5, 0.5 (their center)
// so this will put the layer in the center of the view.
lineLayer.position = layer.position
// finally, set up the shape properties. set the path and stroke etc
lineLayer.path = linePath.CGPath
lineLayer.strokeColor = UIColor.whiteColor().CGColor
lineLayer.lineWidth = 4
// add it to your view's layer and you're done!
layer.addSublayer(lineLayer)
现在,您可以使用Core Animation为lineLayer
上的属性设置动画。