swift - Swift 中简单的画线动画

标签 swift swift2 core-animation drawrect uibezierpath

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

我想做的很简单:在屏幕中央画一条直线并设置动画。听起来很简单,对吧?是的..所以这就是我现在所拥有的。

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 函数中。真的吗?需要你们的一些解释。谢谢!

Image

最佳答案

你不应该像这样在 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 上的属性设置动画。

关于swift - Swift 中简单的画线动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085498/

相关文章:

swift - 为什么 Firebase Analytics 数据没有显示在 BigQuery 中?

ios - 如何使用可选 func textViewDidEndEditing(textView : UITextView) to change text as it's entered?

ios - 需要在所有 VC 中添加通用的 UIBarButtonItem

swift - WatchKit Extension Bridging Header 错误(在 Swift 项目中)

iphone - 在 iPhone 上创建粒子最有效的方法是什么

ios - 当 UITableViewCell 满足所有约束时约束中断

macos - 搜索字符串以查找单词的重复实例

objective-c - 让 CVDisplayLink + 自动引用计数完美结合

iphone - 在iPhone上绘制自定义图形: CALayer vs. CGContext

ios - 内容 View 自动布局