我想在Swift3中绘制一个矩形,并根据手机的电池电量进行绘制,例如,如果电池为100%,则必须完全填充矩形。如果电池是67%,那么填充应该是该矩形宽度的67%。
我对CGRect库和绘图很新。
到目前为止,这是我的尝试:
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)
电池图标基本上已经存在于页面上,只有边框,例如以下形状:
------
| |
------
答案 0 :(得分:2)
这是一个起点。
将代码粘贴到Playground中,然后点击最后一行末尾的Show Result
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)