我有这个项目SwiftySwitch。
我的目标是让圆形展开并减少保持圆形的形状,而不是在动画的每个特定时刻都有一个大于当前圆形高度的圆角半径。
处理圈子增长的代码在这里:
func turnOn() {
let tempView = UIView(frame: CGRect(x: ballDiameter / 2, y: ballDiameter / 2, width: 0, height: 0))
tempView.backgroundColor = onColor
tempView.layer.cornerRadius = ballDiameter / 2
self.addSubview(tempView)
UIView.animate(withDuration: dotTravelTime, animations: { [weak self] in
//RIGHT HERE is the code for the circle to hold it's circular form
if self != nil {
tempView.frame = CGRect(x: 0, y: 0, width: self!.ballDiameter, height: self!.ballDiameter)
tempView.layer.cornerRadius = self!.ballDiameter / 2
}
self?.layoutIfNeeded()
}) { [weak self] _ in
self?.backgroundColor = self!.onColor
tempView.removeFromSuperview()
}
}
func turnOff() {
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: ballDiameter, height: ballDiameter))
tempView.backgroundColor = onColor
self.addSubview(tempView)
self.backgroundColor = offColor
UIView.animate(withDuration: dotTravelTime, animations: { [weak self] in
//RIGHT HERE is the code for the circle to hold it's circular form
if self != nil {
tempView.frame = CGRect(x: self!.ballDiameter / 2, y: self!.ballDiameter / 2, width: 0, height: 0)
tempView.layer.cornerRadius = self!.ballDiameter / 2
}
self?.layoutIfNeeded()
}) { _ in
tempView.removeFromSuperview()
}
}
我说的正确在这里是我处理圆圈动画的地方。我使用临时UIView来处理动画,然后在更改其后面的实际视图的颜色后删除视图。 tempView是您看到的圆形开关随滑动动画而变化。如果您需要有关我的设计的任何信息,请告诉我。我尝试了很多东西,所有的东西都解决了,圆圈是一个正方形或角落半径略大于我想要的。 (我认为它从原始尺寸缩小了一些角落半径,但它很小。
答案 0 :(得分:2)
我的目标是让圆圈扩展并减少保持圆形的形式
然后不要在"愚蠢的"方式(cornerRadius
)。掩盖到圆形路径并为蒙版(和/或路径)的生长/收缩设置动画。
在此示例中,我将黄色视图与其蒙版一起增长。动画故意缓慢(持续时间为2秒),以向您显示此工作顺利进行。黄色视图在左上方包含一个标签,在右下角包含一个标签,因此您可以看到(1)它是一个视图,(2)它是连贯增长的。
答案 1 :(得分:1)
角半径是CALayer的属性,而不是UIView。不幸的是,UIView Animation方法只会捕获UIView相关属性的键值更改。您仍然可以单独为图层属性设置动画,但您需要使用CABasicAnimation来执行此操作。或者,您可以实现drawRect,只使用UIBezierPath绘制一个圆,而不是使用圆角半径。