我创建了一个类,它绘制一个单条形图,在设置时指示百分比值。如何为该栏设置动画,使其从左向右增长?
我已经拥有的动画功能无法像它希望的那样工作......
class EasyLineView : UIView {
var fillRect = CGRect.init(x: 0, y: 0, width: 0, height: 0)
var percentValue: CGFloat = 0 {
didSet {
self.layoutIfNeeded()
}
}
var orientation: BarOrientation = .vertical
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.black
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
print("drawing with \(rect.size.width)")
let r = self.bounds // the view's bounds
let ctx = UIGraphicsGetCurrentContext() // get the current context
ctx!.setFillColor(UIColor.yellow.cgColor) // set fill color to the given color if it's provided, else use clearColor
if (self.orientation == .vertical){
fillRect = CGRect.init(x: 0, y: 0, width: r.size.width, height: percentValue*r.size.height)
} else {
fillRect = CGRect.init(x: 0, y: 0, width: percentValue*r.size.width, height: r.size.height)
}
ctx!.fill(fillRect)
}
// does not work
func animate(){
UIView.animate(withDuration: 5, delay: 0, animations: {
self.layoutIfNeeded()
})
}
}
最佳答案
别那样做。在 draw(_:)
中绘制一个盒子会给你带来很差的性能并且没有动画的灵 active 。
如果您想要的只是一个可以配置大小的动画框,请添加一个 subview 并将背景颜色设置为您的绘图颜色。然后,您可以在动画 block 中使用自动布局或手动帧设置,使框以动画形式呈现为您想要的大小。
关于swift - 动画 UIView(在 UIGraphicsGetCurrentContext 上绘图时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46890088/