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