swift - 动画 UIView(在 UIGraphicsGetCurrentContext 上绘图时)

标签 swift animation uikit

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

我已经拥有的动画功能无法像它希望的那样工作......

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/

相关文章:

iphone - 如何使tableview的滚动条在比table框架更小的矩形中滚动?

swift - 等待 boolean 值成为 'true' 的更优雅的方式

ios - Firebase 在 Swift 中检索数据

jquery - 动画在 IE11 上无法正常工作

java - 带有淡入淡出 ImageView 动画的启动画面

ios - UIViewController.dismiss() 不调用 presentingViewController.dismiss()

ios - Swift 3 - 如何截取特定 UITableView 行的屏幕截图

ios - 缩放和重绘 UIScrollView 内容后设置 contentOffset

javascript - 如何制作一个稀有的动画与经常出现的动画一起出现?

ios - 如何在更改尺寸时强制重绘(drawRect) subview ?