美文网首页
颜色叠加算法,UIButton的高亮色设置

颜色叠加算法,UIButton的高亮色设置

作者: zidaneno5 | 来源:发表于2017-02-21 17:05 被阅读426次

理论:https://www.zhihu.com/question/21609387

最近在做一个类似微信公众号下部导航的需求,产品要求导航按钮背景色可以配置,设计师要求点击时背景色要叠加一个透明度为5%的#000000纯黑色。因而有了本文。
如上述理论,颜色叠加在前在后,得到的结果是不一样的。使用的时候请注意区分。
代码:

// 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;
}

注意一点:这里传入的UIColor必须是UIDeviceRGBColor(UIExtendedSRGBColorSpace),类似[UIColor BlackColor];这种是灰度颜色(不知是不是准确,应该是GrayColorSpace),是无法取到RGBA分量的。

得到颜色之后就可以使用如下耳熟能详的代码从颜色生成一个UIImage对象

- (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;
}

之后用UIButtonsetBackgroundImage:forState即可实现点击高亮态的颜色变化。

相关文章

网友评论

      本文标题:颜色叠加算法,UIButton的高亮色设置

      本文链接:https://www.haomeiwen.com/subject/kxuuwttx.html