-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUIImage+AverageColorAddition.m
More file actions
executable file
·78 lines (64 loc) · 2.26 KB
/
Copy pathUIImage+AverageColorAddition.m
File metadata and controls
executable file
·78 lines (64 loc) · 2.26 KB
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
//
// UIImage+UIImageAverageColorAddition.m
// AvgColor
//
// Created by nikolai on 28.08.12.
// Copyright (c) 2012 Savoy Software. All rights reserved.
//
#import "UIImage+AverageColorAddition.h"
@implementation UIImage (UIImageAverageColorAddition)
- (UIColor *)averageColor {
return [self averageColorInFrame:CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale)];
}
- (UIColor *)averageColorInFrame:(CGRect)frame
{
if (!self)
return nil;
CGImageRef rawImageRef = [self CGImage];
// This function returns the raw pixel values
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef));
const UInt8 *rawPixelData = CFDataGetBytePtr(data);
NSUInteger imageHeight = frame.origin.y + frame.size.height;
NSUInteger imageWidth = frame.origin.x + frame.size.width;
NSUInteger bytesPerRow = CGImageGetBytesPerRow(rawImageRef);
NSUInteger stride = CGImageGetBitsPerPixel(rawImageRef) / 8;
// Here I sort the R,G,B, values and get the average over the whole image
unsigned int red = 0;
unsigned int green = 0;
unsigned int blue = 0;
for (int row = frame.origin.y; row < imageHeight; row++) {
const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;
for (int column = frame.origin.x; column < imageWidth; column++) {
red += rowPtr[0];
green += rowPtr[1];
blue += rowPtr[2];
rowPtr += stride;
}
}
CFRelease(data);
CGFloat f = 1.0f / (255.0f * frame.size.width * frame.size.height);
return [UIColor colorWithRed:f * red green:f * green blue:f * blue alpha:1];
}
- (UIColor *)mergedColor
{
CGSize size = {1, 1};
UIGraphicsBeginImageContext(size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
[self drawInRect:(CGRect){.size = size} blendMode:kCGBlendModeCopy alpha:1];
uint8_t* data = (uint8_t*)CGBitmapContextGetData(ctx);
UIColor *color = [UIColor colorWithRed:data[2] / 255.0f
green:data[1] / 255.0f
blue:data[0] / 255.0f
alpha:1];
UIGraphicsEndImageContext();
return color;
}
@end
@implementation UIColor (LightCheck)
- (BOOL)isColorLight {
CGFloat white = 0;
[self getWhite:&white alpha:nil];
return (white >= .7);
}
@end