Search code examples
iosswiftswift3cashapelayercgrect

How to draw a rectangle and fill it with color based on battery level


I want to draw a rectangle in Swift3 and draw based on the battery level of the phone for example, if battery is 100% then rectangle must be filled completely. If battery is 67% then fill should be 67% of that rectangle's width.

I am quite new to the CGRect library and drawing.

Here is my attempt so far:

let layer = CAShapeLayer()

layer.path = UIBezierPath(roundedRect: CGRect(x: battery.frame.origin.x,
                                              y: battery.frame.origin.y,
                                              width: (battery.image?.size.width)!,
                                              height: (battery.image?.size.height)!),
                                              cornerRadius: 0).cgPath
layer.fillColor = UIColor.red.cgColor
view.layer.addSublayer(layer)

battery icon is basically already there on the page with just the border for example in the following shape:

------ | | ------


Solution

  • This is a starting point.

    Paste the code in a Playground and click on Show Result at the end of the last line

    class LevelView : UIView {
    
        init(frame: CGRect, level: CGFloat) {
            super.init(frame: frame)
            self.layer.borderWidth = 1.0
            let levelLayer = CAShapeLayer()
            levelLayer.path = UIBezierPath(roundedRect: CGRect(x: frame.origin.x,
                                                          y: frame.origin.y,
                                                          width: frame.width * level,
                                                          height: frame.height),
                                      cornerRadius: 0).cgPath
            levelLayer.fillColor = UIColor.red.cgColor
            self.layer.addSublayer(levelLayer)
    
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("Required, but Will not be called in a Playground")
        }
    }
    
    
    let view = LevelView(frame: CGRect(x: 0, y: 0, width: 64, height: 32), level: 0.75)