如何制作CGRect动画

时间:2017-01-08 17:36:55

标签: swift3 ios10

如何制作像这样的动画?

override func draw(_ rect: CGRect)
{

    let xPointRect = viewWithTag(1)?.alignmentRect(forFrame: rect).midX
    let yPointRect = viewWithTag(1)?.alignmentRect(forFrame: rect).midY
    let widthSize = self.viewWithTag(1)?.frame.size.width
    let heightSize = self.viewWithTag(1)?.frame.size.height
    let sizeRect = CGSize(width: widthSize! * 0.8, height: heightSize! * 0.4)

    let rectPlacementX = CGFloat(sizeRect.width/2)
    let rectPlacementY = CGFloat(sizeRect.height/2)
    let context2 = UIGraphicsGetCurrentContext()
    context2?.setLineWidth(2.0)
    context2?.setStrokeColor(UIColor.red.cgColor)
    context2?.move(to: CGPoint(x: (xPointRect! - rectPlacementX), y: (yPointRect! - rectPlacementY)))
    context2?.addLine(to: CGPoint(x: (xPointRect! + rectPlacementX), y: (yPointRect! + rectPlacementY)))
    context2?.setLineDash(phase: 3, lengths: dashArray)
    context2?.strokePath()


    context2.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
    UIView.animate(withDuration: 1.0, 
        delay: 0, 
        usingSpringWithDamping: 0.15, 
        initialSpringVelocity: 6.0, 
        options: .allowUserInteraction, 
        animations: { context2.transform = CGAffineTransform.identity },
        completion: nil)
}

我当前的代码无效,因为context2不包含成员.transfer,因为它是CGRect。

如何让这条线具有动画效果?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

CGRect不可见,所以我不明白为什么要为它设置动画。

我假设您要为UIView的帧设置动画。

您可以在动画块中更改UIView的许多属性。它也是框架:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
someParentView.addSubview(view)
UIView.animate(withDuration: 2.5) {
    someUIView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)

}