使用方法 button.backgroundColor = [self mostColor:self.imageViewOne.image];
#pragma mark - 吸取颜色
-(UIColor*)mostColor:(UIImage*)img{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
intbitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
//第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
CGSizethumbSize=CGSizeMake(50,50);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
thumbSize.width,
thumbSize.height,
8,//bits per component
thumbSize.width*4,
colorSpace,
bitmapInfo);
CGRectdrawRect =CGRectMake(0,0, thumbSize.width, thumbSize.height);
CGContextDrawImage(context, drawRect, img.CGImage);
CGColorSpaceRelease(colorSpace);
//第二步 取每个点的像素值
unsignedchar* data =CGBitmapContextGetData(context);
if(data ==NULL)returnnil;
NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
for(intx=0; x
for(inty=0; y
intoffset =4*(x*y);
intred = data[offset];
intgreen = data[offset+1];
intblue = data[offset+2];
intalpha = data[offset+3];
NSArray*clr=@[@(red),@(green),@(blue),@(alpha)];
[clsaddObject:clr];
}
}
CGContextRelease(context);
//第三步 找到出现次数最多的那个颜色
NSEnumerator *enumerator = [cls objectEnumerator];
NSArray*curColor =nil;
NSArray*MaxColor=nil;
NSUIntegerMaxCount=0;
while( (curColor = [enumeratornextObject]) !=nil)
{
NSUIntegertmpCount = [clscountForObject:curColor];
if( tmpCount < MaxCount )continue;
MaxCount=tmpCount;
MaxColor=curColor;
}
return[UIColorcolorWithRed:([MaxColor[0]intValue]/255.0f)green:([MaxColor[1]intValue]/255.0f)blue:([MaxColor[2]intValue]/255.0f)alpha:([MaxColor[3]intValue]/255.0f)];
}