|
import UIKit |
|
import RxSwift |
|
import UIFontComplete |
|
|
|
class RxResourceView: UIView { |
|
|
|
var resourcesCount: [Int32] = [] |
|
let countStringAttributes: [NSAttributedStringKey: Any] = [.font: UIFont(font: Font.georgia, size: 13)!, |
|
.foregroundColor: R.color.lightPrimary()!] |
|
let disposeBag = DisposeBag() |
|
|
|
override init(frame: CGRect) { |
|
super.init(frame: frame) |
|
commonInit() |
|
} |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
super.init(coder: aDecoder) |
|
commonInit() |
|
} |
|
|
|
private func commonInit() { |
|
isUserInteractionEnabled = false |
|
backgroundColor = UIColor.clear |
|
Observable<Int>.interval(1.0, scheduler: MainScheduler.instance) |
|
.map { _ in return Resources.total } |
|
.distinctUntilChanged() |
|
.subscribe(onNext: { [weak self] count in |
|
guard let strongSelf = self else { return } |
|
if strongSelf.resourcesCount.count == 50 { |
|
strongSelf.resourcesCount = Array(strongSelf.resourcesCount.dropFirst()) |
|
} |
|
strongSelf.resourcesCount.append(count) |
|
strongSelf.setNeedsDisplay() |
|
}) |
|
.disposed(by: disposeBag) |
|
} |
|
|
|
override func draw(_ rect: CGRect) { |
|
guard let context = UIGraphicsGetCurrentContext() else { return } |
|
|
|
let graphRect = rect.insetBy(dx: 20, dy: 20) |
|
let lineWidth = graphRect.width / 50 - 1 |
|
let maxValue: CGFloat = CGFloat(resourcesCount.max() ?? 0) |
|
|
|
context.setLineWidth(lineWidth) |
|
context.setStrokeColor(R.color.darkPrimary()!.withAlphaComponent(0.2).cgColor) |
|
|
|
var index = 0 |
|
var drawX = graphRect.maxX - lineWidth / 2 |
|
for count in resourcesCount.reversed() { |
|
context.addLines(between: [CGPoint(x: drawX, y: graphRect.maxY), |
|
CGPoint(x: drawX, y: graphRect.maxY - graphRect.height * CGFloat(count) / maxValue)]) |
|
context.strokePath() |
|
drawX -= (lineWidth + 1) |
|
index += 1 |
|
} |
|
|
|
if let currentCount = resourcesCount.last { |
|
let countString = "ResourceCount: \(currentCount)" as NSString |
|
let size = countString.size(withAttributes: countStringAttributes) |
|
countString.draw(in: CGRect(x: graphRect.maxX - size.width, y: graphRect.maxY, width: size.width, height: size.height), |
|
withAttributes: countStringAttributes) |
|
} |
|
} |
|
} |