返回一张图片的主色调

#import 

@interface UIColor (YKD)
/**
 *  返回一张图片的主色调
 */
+ (UIColor *)mostColorWithImage:(UIImage *)image;
@end

//
//  UIColor+YKD.m

#import "UIColor+YKD.h"

@implementation UIColor (YKD)

+ (UIColor *)mostColorWithImage:(UIImage *)image
{
    // 1.先把图片缩小,加快计算速度,但越小结果误差可能越大
    CGSize thumbSize = CGSizeMake(50, 50);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(NULL, thumbSize.width, thumbSize.height, 8, thumbSize.width*4, colorSpace, kCGImageAlphaPremultipliedLast);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    // 2.取每个点的像素值
    unsigned char *data = CGBitmapContextGetData(context);
    if (data == NULL) {
        return nil;
    }
    NSCountedSet *cls = [NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    for (int x=0; x

你可能感兴趣的:(iOS常用分类)