简体   繁体   中英

How to properly use setNeedsDisplay()

In my program, I am using a slider to change the alpha level of the currently selected color.
When the slider changes its value, it calls my setColor() method to update the current color with the new alpha value and to update the uiview which displays the current color.
Inside of this function, I am also trying to update my custom uiview, which is the powerButton as seen below.
I change the color of the inner ring and then redraw it by calling setNeedsDisplay() .
The more I slide and change the color, the program begins to lag more and more.

Is this because of the constant redrawing? Is there a better way to do this?

Also, does setNeedsDisplay() draw over the previous drawing or does it actually update?

  @IBAction func brightnessSliderChanged(sender: UISlider) {
        let currentVal = Int(sender.value)
        let alpha = CGFloat(Int(currentVal)) * 0.01
        brightnessLabel.text = String(currentVal) + "%"
        setColor(currentColor.colorWithAlphaComponent(alpha))
    }
    func setColor(color: UIColor) {
            let alpha = CGFloat(Int(lightBrightnessSlider.value)) * 0.01
            currentColor = color.colorWithAlphaComponent(alpha)
            colorView.backgroundColor = currentColor
            if powerState {
                powerButton.statusColor = currentColor
                powerButton.setNeedsDisplay()
            }
        }

And what the custom UIView class and function looks like

@IBDesignable

class PowerButton: UIView {

    @IBInspectable var buttonColor: UIColor = UIColor.whiteColor()
    @IBInspectable var statusColor: UIColor = UIColor.whiteColor()
    let desiredLineWidth:CGFloat = 3

    override func drawRect(rect: CGRect) {
        drawFillCircle()
        drawRing()
        drawInnerCircle()
    }
    internal func drawFillCircle()->() {

        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)                

        let circlePath = UIBezierPath(
        arcCenter: CGPoint(x:halfSize,y:halfSize),
        radius: CGFloat( CGFloat(halfSize) - (desiredLineWidth / 2)),
        startAngle: CGFloat(0),
        endAngle:CGFloat(M_PI * 2),
        clockwise: true)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.CGPath

        shapeLayer.fillColor = statusColor.CGColor

        layer.addSublayer(shapeLayer)
    }

更改颜色值越多发生延迟的示例

Your app lags because you're adding a shape layer in every call of drawRect() . Thus, the layer hierarchy becomes larger and larger.

You should add the shape layer only once, and merely change its colors and the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM