Skip to content

Instantly share code, notes, and snippets.

@Nirma
Created June 26, 2017 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nirma/79bfa30b733a8b959401aea9e6739b2b to your computer and use it in GitHub Desktop.
Save Nirma/79bfa30b733a8b959401aea9e6739b2b to your computer and use it in GitHub Desktop.
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