Swift中的简单线条绘制动画

Lin*_*nas 1 core-animation drawrect uibezierpath swift swift2

我是新手,对我遇到的这个问题感到沮丧.

我想要做的非常简单:在屏幕中央画一条直线并为其制作动画.听起来很简单吧?是啊..这就是我现在所拥有的.

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)

    }

}
Run Code Online (Sandbox Code Playgroud)

我问的原因是我发现我无法为它设置动画,因为它在drawRect函数中.真的吗?需要你们的一些解释.谢谢!

图片

Chr*_*wik 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)
Run Code Online (Sandbox Code Playgroud)

现在,您可以lineLayer使用Core Animation 设置动画属性.