理論:https://www.zhihu.com/question/21609387
最近在做一個(gè)類似微信公眾號(hào)下部導(dǎo)航的需求奕剃,產(chǎn)品要求導(dǎo)航按鈕背景色可以配置渣窜,設(shè)計(jì)師要求點(diǎn)擊時(shí)背景色要疊加一個(gè)透明度為5%的#000000
純黑色吏垮。因而有了本文障涯。
如上述理論,顏色疊加在前在后膳汪,得到的結(jié)果是不一樣的唯蝶。使用的時(shí)候請(qǐng)注意區(qū)分。
代碼:
// forwordColor 是上層顏色遗嗽,backwordColor是下層顏色
-(UIColor *)colorWithForwordColor:(UIColor *)forwordColor backwordColor:(UIColor *)backwordColor{
const CGFloat *components = CGColorGetComponents(forwordColor.CGColor);
const CGFloat *components2 = CGColorGetComponents(backwordColor.CGColor);
CGFloat red1 = components[0];
CGFloat green1 = components[1];
CGFloat blue1 = components[2];
CGFloat alpha1 = components[3];
CGFloat red2 = components2[0];
CGFloat green2 = components2[1];
CGFloat blue2 = components2[2];
CGFloat alpha2 = components2[3];
CGFloat alpha = 1-(1-alpha1)*(1-alpha2);
CGFloat red = (alpha1*red1+(1-alpha1)*red2*alpha2)/alpha;
CGFloat green = (alpha1*green1+(1-alpha1)*green2*alpha2)/alpha;
CGFloat blue = (alpha1*blue1+(1-alpha1)*blue2*alpha2)/alpha;
UIColor *rColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
return rColor;
}
注意一點(diǎn):這里傳入的UIColor
必須是UIDeviceRGBColor(UIExtendedSRGBColorSpace)
粘我,類似[UIColor BlackColor];
這種是灰度顏色(不知是不是準(zhǔn)確,應(yīng)該是GrayColorSpace),是無(wú)法取到RGBA分量的痹换。
得到顏色之后就可以使用如下耳熟能詳?shù)拇a從顏色生成一個(gè)UIImage
對(duì)象
- (UIImage*) createImageWithColor: (UIColor*) color
{
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
之后用UIButton
的 setBackgroundImage:forState
即可實(shí)現(xiàn)點(diǎn)擊高亮態(tài)的顏色變化征字。