-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIImage+ChameleonPrivate.m
executable file
·74 lines (57 loc) · 2.52 KB
/
UIImage+ChameleonPrivate.m
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
//
// UIImage+ChameleonPrivate.m
// Chameleon
//
// Created by Vicc Alexander on 6/8/15.
// Copyright (c) 2015 Vicc Alexander. All rights reserved.
//
#import "UIImage+ChameleonPrivate.h"
@implementation UIImage (ChameleonPrivate)
// Would not have been possible without - http://stackoverflow.com/a/1262893
+ (UIColor *)colorFromImage:(UIImage *)image atPoint:(CGPoint)point {
//Encapsulate our image
CGImageRef imageRef = image.CGImage;
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
//Specify the colorspace we're in
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//Extract the data we need
unsigned char *rawData = calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow,
colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
//Release colorspace
CGColorSpaceRelease(colorSpace);
//Draw and release image
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
//rawData now contains the image data in RGBA8888
NSInteger byteIndex = (bytesPerRow * point.y) + (point.x * bytesPerPixel);
//Define our RGBA values
CGFloat red = (rawData[byteIndex] * 1.f) / 255.f;
CGFloat green = (rawData[byteIndex + 1] * 1.f) / 255.f;
CGFloat blue = (rawData[byteIndex + 2] * 1.f) / 255.f;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.f;
//Free our rawData
free(rawData);
//Return color
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark - Instance Methods
- (UIImage *)imageScaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
[self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end