gpt4 book ai didi

ios - 自定义 UIView 中的动画 setFillColor 颜色变化

转载 作者:搜寻专家 更新时间:2023-11-01 07:00:51 25 4
gpt4 key购买 nike

我有一个名为 CircleView 的自定义 UIView,它本质上是一个彩色椭圆。我用来为椭圆着色的颜色属性是使用图形上下文中的 setFillColor 呈现的。我想知道是否有一种方法可以为颜色变化设置动画,因为当我运行动画/过渡时,颜色会立即改变而不是动画。

示例设置

let c = CircleView()
c.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
c.color = UIColor.blue
c.backgroundColor = UIColor.clear
self.view.addSubview(c)

UIView.transition(with: c, duration: 5, options: .transitionCrossDissolve, animations: {
c.color = UIColor.red // Not animated
})

UIView.animate(withDuration: 5) {
c.color = UIColor.yellow // Not animated
}

圆形 View

class CircleView : UIView {

var color = UIColor.blue {
didSet {
setNeedsDisplay()
}
}

override init(frame: CGRect) {
super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override func draw(_ rect: CGRect) {

guard let context = UIGraphicsGetCurrentContext() else {return}

context.addEllipse(in: rect)
context.setFillColor(color.cgColor)
context.fillPath()

}
}

最佳答案

您可以为图层的 backgroundColor 使用内置动画支持。
虽然制作圆圈的最简单方法是将您的 View 设为正方形(例如,使用纵横比约束),然后将 cornerRadius 设置为宽度或高度的一半,但我假设您想要一些东西更高级,这就是你使用路径的原因。 我对此的解决方案是这样的:

class CircleView : UIView {

var color = UIColor.blue {
didSet {
layer.backgroundColor = color.cgColor
}
}

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}

// Setup the view, by setting a mask and setting the initial color
private func setup(){
layer.mask = shape
layer.backgroundColor = color.cgColor
}

// Change the path in case our view changes it's size
override func layoutSubviews() {
super.layoutSubviews()
let path = CGMutablePath()
// add an elipse, or what ever path/shapes you want
path.addEllipse(in: bounds)
// Created an inverted path to use as a mask on the view's layer
shape.path = UIBezierPath(cgPath: path).reversing().cgPath
}
// this is our shape
private var shape = CAShapeLayer()
}

或者如果你真的需要一个简单的圆圈,就像这样:

class CircleView : UIView {

var color = UIColor.blue {
didSet {
layer.backgroundColor = color.cgColor
}
}

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}

private func setup(){
clipsToBounds = true
layer.backgroundColor = color.cgColor
}

override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
}
}

无论哪种方式,这都会很好地制作动画:

UIView.animate(withDuration: 5) {
self.circle.color = .red
}

关于ios - 自定义 UIView 中的动画 setFillColor 颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com