5 // Created by Pawel Dabrowski on 20/09/2018.
6 // Copyright © 2018 Fundacja Nowoczesna Polska. All rights reserved.
11 // from https://stackoverflow.com/a/46047570/871425
12 class ProgressLabel: UIView {
14 private var privateColor = UIColor.green
15 @IBInspectable var color: UIColor {
19 privateColor = newValue
23 var textColor = UIColor.white
24 var font = UIFont.systemFont(ofSize: 15)
25 var fullProgress: Bool = false
26 var customText: String? {
33 var progress: Float = 0 {
36 progress = Float.minimum(100.0, Float.maximum(progress, 0.0))
37 self.setNeedsDisplay()
41 override func draw(_ rect: CGRect) {
42 let context = UIGraphicsGetCurrentContext()!
44 // Set up environment.
45 let size = self.bounds.size
47 layer.borderColor = privateColor.cgColor
48 layer.borderWidth = 1.0
49 layer.cornerRadius = 10
53 var progressMessage = NSString(format:"Pobieranie %d%%", Int(prg))
55 if let customText = customText{
56 prg = fullProgress ? 100 : 0
57 progressMessage = customText as NSString
60 // Prepare progress as a string.
61 var attributes: [NSAttributedStringKey:Any] = [ NSAttributedStringKey.font : font ]
62 let textSize = progressMessage.size(withAttributes: attributes)
63 let progressX = ceil(CGFloat(prg) / 100 * size.width)
64 let textPoint = CGPoint(x: ceil((size.width - textSize.width) / 2.0), y: ceil((size.height - textSize.height) / 2.0))
66 // Draw background + foreground text
67 privateColor.setFill()
68 context.fill(self.bounds)
69 attributes[NSAttributedStringKey.foregroundColor] = textColor
70 let rct = CGRect(x: 20, y: 12, width: bounds.size.width - 20, height: bounds.size.height - 13)
71 progressMessage.draw(in: rct, withAttributes: attributes)
73 // Clip the drawing that follows to the remaining progress' frame.
75 let remainingProgressRect = CGRect(x: progressX, y: 0.0, width: size.width - progressX, height: size.height)
76 context.addRect(remainingProgressRect)
79 // Draw again with inverted colors.
81 context.fill(self.bounds)
82 attributes[NSAttributedStringKey.foregroundColor] = privateColor
83 progressMessage.draw(in: rct, withAttributes: attributes)
85 context.restoreGState()