如何动画缩放和移动UILabel,然后在完成后将其变换设置回身份并保留其帧?

时间:2017-06-26 21:55:38

标签: ios swift uiview cgaffinetransform

我有一个UILabel,我试图扩展和翻译,我想动画这个。我是通过在transform块中设置UIView.animate来完成此操作的。动画完成后,我想将视图transform设置回.identity并更新其框架,使其保持在CGAffineTransform移动它的确切位置。伪代码:

func animateMovement(label: UILabel,
                     newWidth: CGFloat,
                     newHeight: CGFloat,
                     newOriginX: CGFloat,
                     newOriginY: CGFloat)
{        
    UIView.animate(withDuration: duration, animations: {
        label.transform = ??? // Something that moves it to the new location and new size
    }) {
        label.frame = ??? // The final frame from the above animation
        label.transform = CGAffineTransform.identity
    }
}

至于为什么我不简单地在动画块中分配新帧:我在标签内部有文本我想用动画缩放,这在动画改变帧而不是变换时是不可能的

我有坐标空间问题,我可以告诉他,因为在动画之后它不在正确的位置(标签的来源错误)。

1 个答案:

答案 0 :(得分:2)

这是我想出的答案。这将在动画的持续时间内缩放内容,然后重置对象以在完成时进行标识转换。

static func changeFrame(label: UILabel,
                        toOriginX newOriginX: CGFloat,
                        toOriginY newOriginY: CGFloat,
                        toWidth newWidth: CGFloat,
                        toHeight newHeight: CGFloat,
                        duration: TimeInterval)
{
    let oldFrame = label.frame
    let newFrame = CGRect(x: newOriginX, y: newOriginY, width: newWidth, height: newHeight)

    let translation = CGAffineTransform(translationX: newFrame.midX - oldFrame.midX,
                                        y: newFrame.midY - oldFrame.midY)
    let scaling = CGAffineTransform(scaleX: newFrame.width / oldFrame.width,
                                    y: newFrame.height / oldFrame.height)

    let transform = scaling.concatenating(translation)

    UIView.animate(withDuration: duration, animations: {
        label.transform = transform
    }) { _ in
        label.transform = .identity
        label.frame = newFrame
    }
}