我正在尝试创建动画,在其中将矩形的颜色从橙色更改为蓝色。这是我创建矩形并将背景颜色设置为橙色的地方:
let colorView = UIView(frame: CGRect(x: 250, y: 500, width: 75, height: 75))
colorView.backgroundColor = UIColor.orange
这是我在其中添加动画及其下面的动画功能定义的地方
let colorChangeAnimation = constructColorChangeAnimation()
colorView.layer.add(colorChangeAnimation, forKey: "color")
private func constructColorChangeAnimation() -> CABasicAnimation {
let ColorChangeAnimation = CABasicAnimation(keyPath: "backgroundColor")
ColorChangeAnimation.fromValue = UIColor.orange
ColorChangeAnimation.toValue = UIColor.blue
return ColorChangeAnimation
}
此实现似乎无法正常运行,我不确定是否需要更改。该文档说fromValue和toValue应该是更改动画的方式,但似乎并不想工作。 (仅供参考,我本来确实有一个用于动画功能的duration变量,但那时也没有用)
答案 0 :(得分:0)
您应该使用UIColor.orange.cgColor
animation.fromValue = UIColor.orange.cgColor
animation.duration = 3
UIView动画更容易
colorView.backgroundColor = UIColor.orange
UIView.animate(withDuration: 3) {
self.aview.backgroundColor = UIColor.blue
}
答案 1 :(得分:0)
尝试这个;
let colourAnim = CABasicAnimation(keyPath: "backgroundColor")
colourAnim.fromValue = self.colorView.backgroundColor
colourAnim.toValue = UIColor.blue.cgColor
colourAnim.duration = 1.0
self.colorView.addAnimation(colourAnim, forKey: "colourAnimation")
self.colorView.backgroundColor = UIColor.blue.cgColor
您应该在动画之后设置视图的背景色,并使用o .cgColor
答案 2 :(得分:0)
像这样使用UIView.animate: 在您的类控制器下,声明视图和按钮(在我的示例中,我添加角半径以获得更可爱的结果)
let chamgeButton = UIButton(type: .system)
let orangeView = UIView()
在viewDidLoad中构造它们,显示并添加约束:
orangeView.backgroundColor = .orange
orangeView.layer.cornerRadius = 8
orangeView.clipsToBounds = true
orangeView.translatesAutoresizingMaskIntoConstraints = false
chamgeButton.backgroundColor = .red
chamgeButton.setTitle("changeColor", for: .normal)
chamgeButton.setTitleColor(.white, for: .normal)
chamgeButton.layer.cornerRadius = 8
chamgeButton.clipsToBounds = true
chamgeButton.addTarget(self, action: #selector(handleChangeColor), for: .touchUpInside)
chamgeButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(orangeView)
orangeView.heightAnchor.constraint(equalToConstant: 200).isActive = true
orangeView.widthAnchor.constraint(equalToConstant: 200).isActive = true
orangeView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
orangeView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
view.addSubview(chamgeButton)
chamgeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true
chamgeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
chamgeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
chamgeButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
现在添加目标按钮功能以更改颜色:
@objc fileprivate func handleChangeColor() {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.orangeView.backgroundColor = .blue
self.view.layoutIfNeeded()
}, completion: nil)
}
这是结果: