Created
June 26, 2017 06:50
-
-
Save Nirma/79bfa30b733a8b959401aea9e6739b2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
@IBDesignable final class ProgressBarView: UIView { | |
@IBInspectable var barColor: UIColor = UIColor.ex.red | |
@IBInspectable var trackColor: UIColor = UIColor.ex.gray | |
@IBInspectable var barThickness: CGFloat = 8.0 | |
@IBInspectable var barPadding: CGFloat = 0.0 | |
@IBInspectable var trackPadding: CGFloat = 0.0 | |
@IBInspectable var progressValue: Int = 0 { | |
didSet { | |
progressValue = max(min(progressValue, 100), 0) | |
setNeedsDisplay() | |
} | |
} | |
// MARK: - Draw | |
override func draw(_ rect: CGRect) { | |
guard let context = UIGraphicsGetCurrentContext() else { return } | |
context.saveGState() | |
drawTrack(with: context) | |
drawProgressBar(with: context) | |
context.restoreGState() | |
} | |
private var percentage: CGFloat { | |
let calibratedWidth = frame.size.width - (barPadding * 2) - (trackOffset * 2) | |
let progress = (CGFloat(progressValue) / 100) * calibratedWidth | |
return progress < 0 ? barPadding : progress | |
} | |
private var trackHeight: CGFloat { | |
return barThickness + trackPadding | |
} | |
private var trackOffset: CGFloat { | |
return trackHeight / 2.0 | |
} | |
private func drawTrack(with context: CGContext) { | |
context.setStrokeColor(trackColor.cgColor) | |
context.beginPath() | |
context.setLineWidth(trackHeight) | |
context.move(to: CGPoint(x: barPadding + trackOffset, y: frame.size.height / 2)) | |
context.addLine(to: CGPoint(x: frame.size.width - barPadding - trackOffset, y: frame.size.height / 2)) | |
context.setLineCap(CGLineCap.round) | |
context.strokePath() | |
} | |
private func drawProgressBar(with context: CGContext) { | |
context.setStrokeColor(barColor.cgColor) | |
context.setLineWidth(barThickness) | |
context.beginPath() | |
context.move(to: CGPoint(x: barPadding + trackOffset, y: frame.size.height / 2)) | |
context.addLine(to: CGPoint(x: barPadding + trackOffset + percentage, y: frame.size.height / 2)) | |
context.setLineCap(CGLineCap.round) | |
context.strokePath() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment