公司要求搞一個根據(jù)banner主顏色要改變導航條以及背景顏色的需求
首先想到的是要讓后臺加個顏色字段,然后直接讀取固歪。后來想試試本地實現(xiàn)自力更生
然后貼了一段傳入圖片然后根據(jù)圖片的每一個點計算顏色取顏色出現(xiàn)最多的那個為主色調(diào)
+(UIColor*)mostColor:(UIImage*)image
{
#if?__IPHONE_OS_VERSION_MAX_ALLOWED?>?__IPHONE_6_1
?int bitmapInfo =kCGBitmapByteOrderDefault|kCGImageAlphaPremultipliedLast;
#else
?intbitmapInfo?=?kCGImageAlphaPremultipliedLast
#endif
? ? //第一步?先把圖片縮小?加快計算速度.?但越小結(jié)果誤差可能越大
? ? CGSizethumbSize=CGSizeMake(image.size.width/2,image.size.height/2);
? ? CGColorSpaceRef colorSpace =CGColorSpaceCreateDeviceRGB();
? ? CGContextRefcontext =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,image.CGImage);
? ? CGColorSpaceRelease(colorSpace);
? ? //第二步?取每個點的像素值
? ? unsigned char*data=CGBitmapContextGetData(context);
? ? if(data==NULL)return nil;
? ? NSCountedSet*cls=[NSCountedSetsetWithCapacity:thumbSize.width*thumbSize.height];
//為了降低遍歷次數(shù) 擴大了像素的點 ? 但是會影響取值的準確性
? ? for(intx=thumbSize.width/6; x<(thumbSize.width*2/3); x+=15)
? ? {
?? ? ? ? ? for(inty=20; y<(thumbSize.height/2)+20; y+=10)
?? ? ? ? ? {
?? ? ? ? ? ? ? intoffset =4*(x*y);
?? ? ? ? ? ? ? intred =data[offset];
?? ? ? ? ? ? ? intgreen =data[offset+1];
?? ? ? ? ? ? ? intblue = data[offset+2];
?? ? ? ? ? ? ? intalpha = data[offset+3];
?? ? ? ? ? ? ? if(alpha>0)
?? ? ? ? ? ? ? {//去除透明
?? ? ? ? ? ? ? ? ? if(red==255&&green==255&&blue==255)
?? ? ? ? ? ? ? ? ? {//去除白色
?? ? ? ? ? ? ? ? ? }else
?? ? ? ? ? ? ? ? ? {
?? ? ? ? ? ? ? ? ? ? ? NSArray*clr=@[@(red),@(green),@(blue),@(alpha)];
?? ? ? ? ? ? ? ? ? ? ? [clsaddObject:clr];
?? ? ? ? ? ? ? ? ? }
?? ? ? ? ? ? ? }
?? ? ? ? ? }
? ? }
? ? CGContextRelease(context);
? ? //第三步?找到出現(xiàn)次數(shù)最多的那個顏色
? ? NSEnumerator*enumerator=[clsobjectEnumerator];
? ? NSArray*curColor =nil;
? ? NSArray*MaxColor=nil;
? ? NSUIntegerMaxCount=0;
? ? while((curColor =[enumeratornextObject])!=nil)
? ? {
? ? ? ? NSUIntegertmpCount=[clscountForObject:curColor];
? ? ? ? if(tmpCountcontinue;
? ? ? ? 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)];
}