最近的開發(fā)過程中,有一個功能是根據(jù)銀行的圖標(biāo)來確定cell的背景顏色,即獲取圖片的主色調(diào)。網(wǎng)上搜索了一些方法,發(fā)現(xiàn)有位博主分享了一個很好的代碼方法,不過效果感覺不是特別明顯,或者說變化不是很大,如圖:
后來仔細(xì)想了一下,代碼和方法是沒有錯誤的,但是我們把透明顏色以及白色也計(jì)算進(jìn)去了,所以效果才會那么不明顯。所以在進(jìn)行rgb色值獲取的時候,排除掉透明色及白色即可,修改后的代碼如下:
//根據(jù)圖片獲取圖片的主色調(diào)
+(UIColor*)mostColor:(UIImage*)image{
#if?__IPHONE_OS_VERSION_MAX_ALLOWED?>?__IPHONE_6_1
intbitmapInfo?=?kCGBitmapByteOrderDefault?|?kCGImageAlphaPremultipliedLast;
#else
intbitmapInfo?=?kCGImageAlphaPremultipliedLast;
#endif
//第一步?先把圖片縮小?加快計(jì)算速度.?但越小結(jié)果誤差可能越大
CGSize?thumbSize=CGSizeMake(image.size.width/2,?image.size.height/2);
CGColorSpaceRef?colorSpace?=?CGColorSpaceCreateDeviceRGB();
CGContextRef?context?=?CGBitmapContextCreate(NULL,
thumbSize.width,
thumbSize.height,
8,//bits?per?component
thumbSize.width*4,
colorSpace,
bitmapInfo);
CGRect?drawRect?=?CGRectMake(0,0,?thumbSize.width,?thumbSize.height);
CGContextDrawImage(context,?drawRect,?image.CGImage);
CGColorSpaceRelease(colorSpace);
//第二步?取每個點(diǎn)的像素值
unsignedchar*?data?=?CGBitmapContextGetData?(context);
if(data?==NULL)returnnil;
NSCountedSet*cls=[NSCountedSetsetWithCapacity: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];
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;
NSUInteger?MaxCount=0;
while(?(curColor?=?[enumeratornextObject])?!=nil)
{
NSUInteger?tmpCount?=?[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)];
}
最后的效果也是特別明顯的,如圖:
源文章的url地址:http://www.cocoachina.com/bbs/read.php?tid=181490.