代码之家  ›  专栏  ›  技术社区  ›  Pascal

动画UIView(在UIGraphicsGetCurrentContext上绘制时)

  •  0
  • Pascal  · 技术社区  · 8 年前

    我创建了一个类,它绘制一个条形图,当设置一个条形图时,该条形图指示一个百分比值。如何设置条的动画,使其从左向右增长?

    动画功能,我已经没有工作,因为它希望它。。。

    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()
        })
    }
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   jrturton    8 年前

    draw(_:) 将给你较差的性能和动画没有灵活性。

    如果您只需要一个可以配置其大小的可设置动画的框,请添加子视图并将背景颜色设置为绘图颜色。然后,可以在动画块中使用“自动布局”或“手动帧设置”使长方体设置为所需大小的动画。