2

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:

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

fscore
  • 2,567
  • 7
  • 40
  • 74
  • Since the battery level value is between 0.0 and 1.0 the width is simply `image.width * batteryLevel` – vadian Jun 26 '17 at 15:46
  • unable to draw that as I'm new to drawing it and filling color. The math is not hard here – fscore Jun 26 '17 at 15:48

1 Answers1

3

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)
vadian
  • 274,689
  • 30
  • 353
  • 361