You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
15 KiB

5 years ago
  1. //
  2. // M13ProgressViewStripedBar.m
  3. // M13ProgressView
  4. //
  5. /*Copyright (c) 2013 Brandon McQuilkin
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  7. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  8. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  9. */
  10. #import "M13ProgressViewStripedBar.h"
  11. @interface M13ProgressViewStripedBar ()
  12. /**The start progress for the progress animation.*/
  13. @property (nonatomic, assign) CGFloat animationFromValue;
  14. /**The end progress for the progress animation.*/
  15. @property (nonatomic, assign) CGFloat animationToValue;
  16. /**The start time interval for the animaiton.*/
  17. @property (nonatomic, assign) CFTimeInterval animationStartTime;
  18. /**Link to the display to keep animations in sync.*/
  19. @property (nonatomic, strong) CADisplayLink *displayLink;
  20. /**Allow us to write to the progress.*/
  21. @property (nonatomic, readwrite) CGFloat progress;
  22. /**The layer that contains the progress layer. That also masks the progress layer.*/
  23. @property (nonatomic, retain) CALayer *progressSuperLayer;
  24. /**The layer that displays progress in the progress bar.*/
  25. @property (nonatomic, retain) CALayer *progressLayer;
  26. /**The layer that masks the stripes of the progress layer.*/
  27. @property (nonatomic, retain) CAShapeLayer *progressMaskLayer;
  28. /**The mask layer for the progress layer.*/
  29. @property (nonatomic, retain) CAShapeLayer *maskLayer;
  30. /**The background layer that displays the border.*/
  31. @property (nonatomic, retain) CAShapeLayer *backgroundLayer;
  32. /**The layer that is used to animate indeterminate progress.*/
  33. @property (nonatomic, retain) CALayer *indeterminateLayer;
  34. /**The action currently being performed.*/
  35. @property (nonatomic, assign) M13ProgressViewAction currentAction;
  36. /**The stripes layer.*/
  37. @property (nonatomic, retain) CALayer *stripesLayer;
  38. @end
  39. @implementation M13ProgressViewStripedBar
  40. {
  41. UIColor *_currentColor;
  42. }
  43. @dynamic progress;
  44. #pragma mark Initalization and setup
  45. - (id)init
  46. {
  47. self = [super init];
  48. if (self) {
  49. [self setup];
  50. }
  51. return self;
  52. }
  53. - (id)initWithFrame:(CGRect)frame
  54. {
  55. self = [super initWithFrame:frame];
  56. if (self) {
  57. [self setup];
  58. }
  59. return self;
  60. }
  61. - (id)initWithCoder:(NSCoder *)aDecoder
  62. {
  63. self = [super initWithCoder:aDecoder];
  64. if (self) {
  65. [self setup];
  66. }
  67. return self;
  68. }
  69. - (void)setup
  70. {
  71. //Set own background color
  72. self.backgroundColor = [UIColor clearColor];
  73. //Set defauts
  74. self.animationDuration = .3;
  75. _cornerType = M13ProgressViewStripedBarCornerTypeSquare;
  76. _cornerRadius = 3.0;
  77. _stripeWidth = 7.0;
  78. _borderWidth = 1.0;
  79. _showStripes = YES;
  80. //Set default colors
  81. self.primaryColor = [UIColor colorWithRed:0 green:122/255.0 blue:1.0 alpha:1.0];
  82. self.secondaryColor = [UIColor colorWithRed:181/255.0 green:182/255.0 blue:183/255.0 alpha:1.0];
  83. self.stripeColor = [UIColor whiteColor];
  84. _currentColor = self.primaryColor;
  85. //BackgroundLayer
  86. _backgroundLayer = [CAShapeLayer layer];
  87. _backgroundLayer.strokeColor = self.secondaryColor.CGColor;
  88. _backgroundLayer.fillColor = nil;
  89. _backgroundLayer.lineWidth = _borderWidth;
  90. [self.layer addSublayer:_backgroundLayer];
  91. //Main mask layer
  92. _progressSuperLayer = [CALayer layer];
  93. _maskLayer = [CAShapeLayer layer];
  94. _maskLayer.fillColor = [UIColor blackColor].CGColor;
  95. _maskLayer.backgroundColor = [UIColor clearColor].CGColor;
  96. _progressSuperLayer.mask = _maskLayer;
  97. [self.layer addSublayer:_progressSuperLayer];
  98. //ProgressLayer
  99. _progressLayer = [CALayer layer];
  100. _progressMaskLayer = [CAShapeLayer layer];
  101. _progressMaskLayer.fillColor = [UIColor whiteColor].CGColor;
  102. _progressMaskLayer.backgroundColor = [UIColor clearColor].CGColor;
  103. _progressLayer.mask = _progressMaskLayer;
  104. [_progressSuperLayer addSublayer:_progressLayer];
  105. _stripesLayer = [CALayer layer];
  106. [_progressLayer addSublayer:_stripesLayer];
  107. //Layout
  108. [self layoutSubviews];
  109. //Start stripes animation
  110. [self setAnimateStripes:YES];
  111. }
  112. #pragma mark Appearance
  113. - (void)setPrimaryColor:(UIColor *)primaryColor
  114. {
  115. [super setPrimaryColor:primaryColor];
  116. if (_currentAction == M13ProgressViewActionNone) {
  117. _currentColor = self.primaryColor;
  118. }
  119. [self setNeedsDisplay];
  120. }
  121. - (void)setSecondaryColor:(UIColor *)secondaryColor
  122. {
  123. [super setSecondaryColor:secondaryColor];
  124. _backgroundLayer.strokeColor = self.secondaryColor.CGColor;
  125. [self setNeedsDisplay];
  126. }
  127. - (void)setStripeColor:(UIColor *)stripeColor
  128. {
  129. _stripeColor = stripeColor;
  130. }
  131. - (void)setCornerType:(M13ProgressViewStripedBarCornerType)cornerType
  132. {
  133. _cornerType = cornerType;
  134. [self setNeedsDisplay];
  135. }
  136. - (void)setCornerRadius:(CGFloat)cornerRadius
  137. {
  138. _cornerRadius = cornerRadius;
  139. [self setNeedsDisplay];
  140. }
  141. - (void)setStripeWidth:(CGFloat)stripeWidth
  142. {
  143. _stripeWidth = stripeWidth;
  144. [self invalidateIntrinsicContentSize];
  145. [self setNeedsDisplay];
  146. }
  147. - (void)setBorderWidth:(CGFloat)borderWidth
  148. {
  149. _borderWidth = borderWidth;
  150. _backgroundLayer.lineWidth = borderWidth;
  151. [self invalidateIntrinsicContentSize];
  152. [self setNeedsDisplay];
  153. }
  154. - (void)setShowStripes:(BOOL)showStripes
  155. {
  156. _showStripes = showStripes;
  157. [self drawStripes];
  158. }
  159. - (void)setAnimateStripes:(BOOL)animateStripes
  160. {
  161. _animateStripes = animateStripes;
  162. //reset the animations
  163. [_stripesLayer removeAllAnimations];
  164. if (_animateStripes) {
  165. //Set the stripes frame
  166. _stripesLayer.frame = CGRectMake(0, 0, self.bounds.size.width + (4 * _stripeWidth), self.bounds.size.height);
  167. //Add the animation
  168. //Create the animation
  169. CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
  170. animation.duration = 2 * self.animationDuration;
  171. animation.repeatCount = HUGE_VALF;
  172. animation.removedOnCompletion = YES;
  173. animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(- (2 *_stripeWidth) + (self.bounds.size.width / 2), self.bounds.size.height / 2.0)];
  174. animation.toValue = [NSValue valueWithCGPoint:CGPointMake(0 + (self.bounds.size.width / 2.0), self.bounds.size.height / 2.0)];
  175. [_stripesLayer addAnimation:animation forKey:@"position"];
  176. }
  177. }
  178. #pragma mark Actions
  179. - (void)setProgress:(CGFloat)progress animated:(BOOL)animated
  180. {
  181. if (animated == NO) {
  182. if (_displayLink) {
  183. //Kill running animations
  184. [_displayLink invalidate];
  185. _displayLink = nil;
  186. }
  187. [super setProgress:progress animated:NO];
  188. [self setNeedsDisplay];
  189. } else {
  190. _animationStartTime = CACurrentMediaTime();
  191. _animationFromValue = self.progress;
  192. _animationToValue = progress;
  193. if (!_displayLink) {
  194. //Create and setup the display link
  195. [self.displayLink invalidate];
  196. self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateProgress:)];
  197. [self.displayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
  198. } /*else {
  199. //Reuse the current display link
  200. }*/
  201. }
  202. }
  203. - (void)animateProgress:(CADisplayLink *)displayLink
  204. {
  205. dispatch_async(dispatch_get_main_queue(), ^{
  206. CGFloat dt = (displayLink.timestamp - self.animationStartTime) / self.animationDuration;
  207. if (dt >= 1.0) {
  208. //Order is important! Otherwise concurrency will cause errors, because setProgress: will detect an animation in progress and try to stop it by itself. Once over one, set to actual progress amount. Animation is over.
  209. [self.displayLink invalidate];
  210. self.displayLink = nil;
  211. [super setProgress:self.animationToValue animated:NO];
  212. [self setNeedsDisplay];
  213. return;
  214. }
  215. //Set progress
  216. [super setProgress:self.animationFromValue + dt * (self.animationToValue - self.animationFromValue) animated:YES];
  217. [self setNeedsDisplay];
  218. });
  219. }
  220. - (void)performAction:(M13ProgressViewAction)action animated:(BOOL)animated
  221. {
  222. if (action == M13ProgressViewActionNone && _currentAction != M13ProgressViewActionNone) {
  223. _currentColor = self.primaryColor;
  224. } else if (action == M13ProgressViewActionSuccess && _currentAction != M13ProgressViewActionSuccess) {
  225. _currentColor = [UIColor colorWithRed:63.0f/255.0f green:226.0f/255.0f blue:80.0f/255.0f alpha:1];
  226. } else if (action == M13ProgressViewActionFailure && _currentAction != M13ProgressViewActionFailure) {
  227. _currentColor = [UIColor colorWithRed:249.0f/255.0f green:37.0f/255.0f blue:0 alpha:1];
  228. }
  229. _currentAction = action;
  230. [self drawStripes];
  231. }
  232. - (void)setIndeterminate:(BOOL)indeterminate
  233. {
  234. [super setIndeterminate:indeterminate];
  235. [self drawProgress];
  236. }
  237. #pragma mark Layout
  238. - (void)layoutSubviews
  239. {
  240. //Set the proper location and size of the text.
  241. _backgroundLayer.frame = self.bounds;
  242. _progressSuperLayer.frame = self.bounds;
  243. _progressMaskLayer.frame = self.bounds;
  244. [self setAnimateStripes:YES];
  245. [self calculateMask];
  246. [self drawStripes];
  247. }
  248. - (CGSize)intrinsicContentSize
  249. {
  250. //Border + border to progress bar margin.
  251. CGFloat base = (_borderWidth * 2) + (_borderWidth * 2) + 1;
  252. //Add some stripes so we can see them.
  253. CGFloat width = base + (2 * _stripeWidth);
  254. return CGSizeMake(width, base);
  255. }
  256. #pragma mark Drawing
  257. - (void)drawRect:(CGRect)rect
  258. {
  259. [self drawProgress];
  260. [self drawBackground];
  261. }
  262. - (void)drawProgress
  263. {
  264. //Calculate the corner radius
  265. CGFloat cornerRadius = 0;
  266. if (_cornerType == M13ProgressViewStripedBarCornerTypeRounded) {
  267. cornerRadius = _cornerRadius;
  268. } else if (_cornerType == M13ProgressViewStripedBarCornerTypeCircle) {
  269. cornerRadius = self.bounds.size.height - (2 * _borderWidth);
  270. }
  271. //Draw the path
  272. CGRect rect;
  273. if (!self.indeterminate) {
  274. rect = CGRectMake(_borderWidth * 2, _borderWidth * 2, (self.bounds.size.width - (4 * _borderWidth)) * self.progress, self.bounds.size.height - (4 * _borderWidth));
  275. } else {
  276. rect = CGRectMake(_borderWidth * 2, _borderWidth * 2, (self.bounds.size.width - (4 * _borderWidth)), self.bounds.size.height - (4 * _borderWidth));
  277. }
  278. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
  279. [_progressMaskLayer setPath:path.CGPath];
  280. }
  281. - (void)drawBackground
  282. {
  283. //Create the path to stroke
  284. //Calculate the corner radius
  285. CGFloat cornerRadius = 0;
  286. if (_cornerType == M13ProgressViewStripedBarCornerTypeRounded) {
  287. cornerRadius = _cornerRadius;
  288. } else if (_cornerType == M13ProgressViewStripedBarCornerTypeCircle) {
  289. cornerRadius = (self.bounds.size.height - _borderWidth) / 2.0;
  290. }
  291. //Draw the path
  292. CGRect rect = CGRectMake(_borderWidth / 2.0, _borderWidth / 2.0, self.bounds.size.width - _borderWidth, self.bounds.size.height - _borderWidth);
  293. UIBezierPath *path;
  294. if (_cornerType == M13ProgressViewStripedBarCornerTypeSquare) {
  295. //Having a 0 corner radius does not display properly since the rect displays like it is not closed.
  296. path = [UIBezierPath bezierPathWithRect:rect];
  297. } else {
  298. path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];;
  299. }
  300. _backgroundLayer.path = path.CGPath;
  301. }
  302. - (void)drawStripes
  303. {
  304. if (!_showStripes && !self.indeterminate) {
  305. //Fill with a solid color
  306. _stripesLayer.backgroundColor = _currentColor.CGColor;
  307. } else {
  308. //Start the image context
  309. UIGraphicsBeginImageContextWithOptions(CGSizeMake(_stripeWidth * 4.0, _stripeWidth * 4.0), NO, [UIScreen mainScreen].scale);
  310. //Fill the background
  311. [_currentColor setFill];
  312. UIBezierPath *fillPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, _stripeWidth * 4.0, _stripeWidth * 4.0)];
  313. [fillPath fill];
  314. //Draw the stripes
  315. [_stripeColor setFill];
  316. for (int i = 0; i < 4; i++) {
  317. //Create the four inital points of the fill shape
  318. CGPoint bottomLeft = CGPointMake(-(_stripeWidth * 4.0), _stripeWidth * 4.0);
  319. CGPoint topLeft = CGPointMake(0, 0);
  320. CGPoint topRight = CGPointMake(_stripeWidth, 0);
  321. CGPoint bottomRight = CGPointMake(-(_stripeWidth * 4.0) + _stripeWidth, _stripeWidth * 4.0);
  322. //Shift all four points as needed to draw all four stripes
  323. bottomLeft.x += i * (2 * _stripeWidth);
  324. topLeft.x += i * (2 * _stripeWidth);
  325. topRight.x += i * (2 * _stripeWidth);
  326. bottomRight.x += i * (2 * _stripeWidth);
  327. //Create the fill path
  328. UIBezierPath *path = [UIBezierPath bezierPath];
  329. [path moveToPoint:bottomLeft];
  330. [path addLineToPoint:topLeft];
  331. [path addLineToPoint:topRight];
  332. [path addLineToPoint:bottomRight];
  333. [path closePath];
  334. [path fill];
  335. }
  336. //Retreive the image
  337. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  338. UIGraphicsEndImageContext();
  339. //Set the background of the progress layer
  340. _stripesLayer.backgroundColor = [UIColor colorWithPatternImage:image].CGColor;
  341. }
  342. }
  343. - (void)calculateMask
  344. {
  345. //Calculate the corner radius
  346. CGFloat cornerRadius = 0;
  347. if (_cornerType == M13ProgressViewStripedBarCornerTypeRounded) {
  348. cornerRadius = _cornerRadius;
  349. } else if (_cornerType == M13ProgressViewStripedBarCornerTypeCircle) {
  350. cornerRadius = self.bounds.size.height - (2 * _borderWidth);
  351. }
  352. //Draw the path
  353. CGRect rect = CGRectMake(_borderWidth * 2, _borderWidth * 2, self.bounds.size.width - (4 * _borderWidth), self.bounds.size.height - (4 * _borderWidth));
  354. UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
  355. //Create the mask
  356. _maskLayer.path = path.CGPath;
  357. //Set the frame
  358. _maskLayer.frame = self.bounds;
  359. _progressSuperLayer.frame = self.bounds;
  360. }
  361. @end