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.

269 lines
8.8 KiB

5 years ago
  1. //
  2. // M13ProgressViewImage.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 "M13ProgressViewImage.h"
  11. @interface M13ProgressViewImage ()
  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 UIImageView that shows the progress image.*/
  23. @property (nonatomic, retain) UIImageView *progressView;
  24. @end
  25. @implementation M13ProgressViewImage
  26. @dynamic progress;
  27. #pragma mark Initalization and setup
  28. - (id)init
  29. {
  30. self = [super init];
  31. if (self) {
  32. [self setup];
  33. }
  34. return self;
  35. }
  36. - (id)initWithFrame:(CGRect)frame
  37. {
  38. self = [super initWithFrame:frame];
  39. if (self) {
  40. [self setup];
  41. }
  42. return self;
  43. }
  44. - (id)initWithCoder:(NSCoder *)aDecoder
  45. {
  46. self = [super initWithCoder:aDecoder];
  47. if (self) {
  48. [self setup];
  49. }
  50. return self;
  51. }
  52. - (void)setup
  53. {
  54. //Set own background color
  55. self.backgroundColor = [UIColor clearColor];
  56. //Set defauts
  57. self.animationDuration = .3;
  58. _progressDirection = M13ProgressViewImageProgressDirectionLeftToRight;
  59. _drawGreyscaleBackground = YES;
  60. //Set the progress view
  61. _progressView = [[UIImageView alloc] init];
  62. _progressView.frame = self.bounds;
  63. _progressView.contentMode = UIViewContentModeScaleAspectFit;
  64. [self addSubview:_progressView];
  65. //Layout
  66. [self layoutSubviews];
  67. }
  68. #pragma mark Appearance
  69. - (void)setProgressDirection:(M13ProgressViewImageProgressDirection)progressDirection
  70. {
  71. _progressDirection = progressDirection;
  72. [self setNeedsDisplay];
  73. }
  74. - (void)setDrawGreyscaleBackground:(BOOL)drawGreyscaleBackground
  75. {
  76. _drawGreyscaleBackground = drawGreyscaleBackground;
  77. [self setNeedsDisplay];
  78. }
  79. - (void)setProgressImage:(UIImage *)progressImage
  80. {
  81. _progressImage = progressImage;
  82. _progressView.image = _progressImage;
  83. [self setNeedsDisplay];
  84. }
  85. #pragma mark Actions
  86. - (void)setProgress:(CGFloat)progress animated:(BOOL)animated
  87. {
  88. if (animated == NO) {
  89. if (_displayLink) {
  90. //Kill running animations
  91. [_displayLink invalidate];
  92. _displayLink = nil;
  93. }
  94. [super setProgress:progress animated:NO];
  95. [self setNeedsDisplay];
  96. } else {
  97. _animationStartTime = CACurrentMediaTime();
  98. _animationFromValue = self.progress;
  99. _animationToValue = progress;
  100. if (!_displayLink) {
  101. //Create and setup the display link
  102. [self.displayLink invalidate];
  103. self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateProgress:)];
  104. [self.displayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
  105. } /*else {
  106. //Reuse the current display link
  107. }*/
  108. }
  109. }
  110. - (void)animateProgress:(CADisplayLink *)displayLink
  111. {
  112. dispatch_async(dispatch_get_main_queue(), ^{
  113. CGFloat dt = (displayLink.timestamp - self.animationStartTime) / self.animationDuration;
  114. if (dt >= 1.0) {
  115. //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.
  116. [self.displayLink invalidate];
  117. self.displayLink = nil;
  118. [super setProgress:self.animationToValue animated:NO];
  119. [self setNeedsDisplay];
  120. return;
  121. }
  122. //Set progress
  123. [super setProgress:self.animationFromValue + dt * (self.animationToValue - self.animationFromValue) animated:YES];
  124. [self setNeedsDisplay];
  125. });
  126. }
  127. - (void)performAction:(M13ProgressViewAction)action animated:(BOOL)animated
  128. {
  129. //Do Nothing
  130. }
  131. - (void)setIndeterminate:(BOOL)indeterminate
  132. {
  133. [super setIndeterminate:indeterminate];
  134. //Do Nothing
  135. }
  136. #pragma mark Layout
  137. - (void)layoutSubviews
  138. {
  139. [super layoutSubviews];
  140. _progressView.frame = self.bounds;
  141. }
  142. - (CGSize)intrinsicContentSize
  143. {
  144. return CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric);
  145. }
  146. #pragma mark Drawing
  147. - (void)drawRect:(CGRect)rect
  148. {
  149. [super drawRect:rect];
  150. [_progressView setImage:[self createImageForCurrentProgress]];
  151. }
  152. - (UIImage *)createImageForCurrentProgress
  153. {
  154. const int ALPHA = 0;
  155. const int RED = 3;
  156. const int GREEN = 2;
  157. const int BLUE = 1;
  158. //Create image rectangle with current image width/height
  159. CGRect imageRect = CGRectMake(0, 0, _progressImage.size.width * _progressImage.scale, _progressImage.size.height * _progressImage.scale);
  160. int width = (int)imageRect.size.width;
  161. int height = (int)imageRect.size.height;
  162. //The pixels will be painted to this array
  163. uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
  164. //Clear the pixels so any transparency is preserved
  165. memset(pixels, 0, width * height * sizeof(uint32_t));
  166. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  167. //Create a context with RGBA pixels
  168. CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
  169. //Paint the bitmap to our context which will fill in the pixels array
  170. CGContextDrawImage(context, CGRectMake(0, 0, width, height), _progressImage.CGImage);
  171. //Calculate the ranges to make greyscale or transparent.
  172. int xFrom = 0;
  173. int xTo = width;
  174. int yFrom = 0;
  175. int yTo = height;
  176. if (_progressDirection == M13ProgressViewImageProgressDirectionBottomToTop) {
  177. yTo = (int)(height * (1 - self.progress));
  178. } else if (_progressDirection == M13ProgressViewImageProgressDirectionTopToBottom) {
  179. yFrom = (int)(height * self.progress);
  180. } else if (_progressDirection == M13ProgressViewImageProgressDirectionLeftToRight) {
  181. xFrom = (int)(width * self.progress);
  182. } else if (_progressDirection == M13ProgressViewImageProgressDirectionRightToLeft) {
  183. xTo = (int)(width * (1 - self.progress));
  184. }
  185. for (int x = xFrom; x < xTo; x++) {
  186. for (int y = yFrom; y < yTo; y++) {
  187. //Get the pixel
  188. uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
  189. //Convert
  190. if (_drawGreyscaleBackground) {
  191. //Convert to grayscale using luma coding: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  192. uint8_t gray = (uint8_t)(0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE]);
  193. // set the pixels to gray
  194. rgbaPixel[RED] = gray;
  195. rgbaPixel[GREEN] = gray;
  196. rgbaPixel[BLUE] = gray;
  197. } else {
  198. //Convert the pixels to transparant
  199. rgbaPixel[RED] = 0;
  200. rgbaPixel[GREEN] = 0;
  201. rgbaPixel[BLUE] = 0;
  202. rgbaPixel[ALPHA] = 0;
  203. }
  204. }
  205. }
  206. // create a new CGImageRef from our context with the modified pixels
  207. CGImageRef image = CGBitmapContextCreateImage(context);
  208. // we're done with the context, color space, and pixels
  209. CGContextRelease(context);
  210. CGColorSpaceRelease(colorSpace);
  211. free(pixels);
  212. // make a new UIImage to return
  213. UIImage *resultUIImage = [UIImage imageWithCGImage:image scale:_progressImage.scale orientation:UIImageOrientationUp];
  214. // we're done with image now too
  215. CGImageRelease(image);
  216. return resultUIImage;
  217. }
  218. @end