如何动画缩放并移动UILabel,然后在完成时将其变换设置回身份并保留其框架?
问题描述:
我有一个UILabel
,我正在尝试缩放和翻译,并且我想动画。我通过将transform
设置为UIView.animate
块来完成此操作。当动画结束后,我想视图的transform
背部设置为.identity
和更新它的框架,使之保持究竟在何处CGAffineTransform
移动它。伪代码:如何动画缩放并移动UILabel,然后在完成时将其变换设置回身份并保留其框架?
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
}
}
至于我为什么不干脆在动画块分配新框架:我的标签里面的文字,我想与动画,动画改变帧时,这是不可能的规模而不是变换。
我有协调的空间问题,我可以因为动画是不是在正确的位置(标签上有错误的原点)后告诉。
答
这里是我想出了答案。这将在动画持续时间内缩放内容,然后重置对象以在完成时进行标识转换。
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
}
}
良好的工作!;恭喜 –