1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- //
- // IHBatteryView.swift
- // Inhealth
- //
- // Created by weclouds on 2020/1/10.
- // Copyright © 2020 weclouds. All rights reserved.
- //
- import UIKit
- class IHBatteryView: UIView {
- //0~ 100
- var batteryValue : Int?{
- didSet{
- setBatteryValue(self.batteryValue ?? 0)
- }
- }
- //电池宽度
- private var b_width :CGFloat?
- //电池高度
- private var b_height :CGFloat?
- //电池高度
- private var b_lineW :CGFloat?
-
- private var batteryView : UIView?
-
- private var layerRight = CAShapeLayer()
- private var batteryLayer = CAShapeLayer()
- override init(frame: CGRect) {
- super.init(frame: frame)
- drawBattery()
- }
-
- required init?(coder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- // override func awakeFromNib() {
- // super.awakeFromNib()
- // drawBattery()
- // }
-
- func drawBattery() {
- let b_x : CGFloat = 1.59
- let b_y : CGFloat = 1.59
- b_height = self.bounds.size.height - 2
- b_width = self.bounds.size.width - 5
- b_lineW = 1.59
-
- //画电池(电池左边)
- let pathLeft = UIBezierPath(roundedRect: CGRect(x: b_x, y: b_y, width: b_width!, height: b_height!), cornerRadius: 2)
-
- batteryLayer.lineWidth = b_lineW!
- batteryLayer.strokeColor = UIColor(hexString: "#05CFAB")?.cgColor
- batteryLayer.fillColor = UIColor.clear.cgColor
- batteryLayer.path = pathLeft.cgPath
- self.layer.addSublayer(batteryLayer)
-
- //画电池(右边电池箭头)
- let pathRight = UIBezierPath()
- pathRight.move(to: CGPoint(x: b_x + b_width! + 1, y: b_y + b_height! / 3))
- pathRight.addLine(to: CGPoint(x: b_x + b_width! + 1, y: b_y + b_height! * 2 / 3))
- layerRight.lineWidth = 2
- layerRight.strokeColor = UIColor(hexString: "#05CFAB")?.cgColor
- layerRight.fillColor = UIColor.clear.cgColor
- layerRight.path = pathRight.cgPath
- self.layer.addSublayer(layerRight)
-
- //电池内部填充
- batteryView = UIView(frame: CGRect(x: b_x + 1.59, y: b_y + b_lineW!, width: 0, height: b_height! - b_lineW! * 2))
- //batteryView?.layer.cornerRadius = 1
- batteryView?.backgroundColor = UIColor(hexString: "#05CFAB")
- addSubview(batteryView!)
-
- }
-
- func setBatteryValue(_ value: Int) {
- if value < 10{
- batteryLayer.strokeColor = UIColor(hexString: "#FF0C4D")?.cgColor
- batteryView?.backgroundColor = UIColor(hexString: "#FF0C4D")
- layerRight.strokeColor = UIColor(hexString: "#FF0C4D")?.cgColor
- }else{
- batteryLayer.strokeColor = UIColor(hexString: "#05CFAB")?.cgColor
- batteryView?.backgroundColor = UIColor(hexString: "#05CFAB")
- layerRight.strokeColor = UIColor(hexString: "#05CFAB")?.cgColor
- }
- var rect = batteryView?.frame
- rect?.size.width = (CGFloat(value) * ( b_width! - b_lineW! * 2 ) ) / 100
- batteryView!.frame = rect!
- }
- }
|