CGColorGetComponents ( UIColor获取RGB值 用于颜色过渡) (二)

这篇博客介绍了如何使用CGColorGetComponents方法从UIColor中获取RGB值,并结合这些值创建颜色过渡动画。通过计算两种颜色在不同比例下的混合,实现了自定义颜色渐变效果。文章还提供了一个用于获取颜色RGB组件的辅助方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

鉴于第一篇文章。写了下面的颜色过渡动画


//颜色过渡  

+(UIColor *)currentColor:(UIColor*)color1 changeColor:(UIColor *)color2 ratio:(CGFloat)ratio

{

    CGFloat components1[3];

    CGFloat components2[3];

    [self getRGBComponents:components1 forColor:color1];

    [self getRGBComponents:components2 forColor:color2];


    CGFloat r = components1[0]*ratio + components2[0]*(1-ratio);

    CGFloat g = components1[1]*ratio + components2[1]*(1-ratio);

    CGFloat b = components1[2]*ratio + components2[2]*(1-ratio);

    return [UIColor colorWithRed:r green:g blue:b alpha:1];

}



//获取components

+ (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();

    unsigned char resultingPixel[4];

    CGContextRef context = CGBitmapContextCreate(&resultingPixel,

                                                 1,

                                                 1,

                                                 8,

                                                 4,

                                                 rgbColorSpace,

                                                 kCGImageAlphaNoneSkipLast);

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));

    CGContextRelease(context);

    CGColorSpaceRelease(rgbColorSpace);

    

    for (int component = 0; component < 3; component++) {

        components[component] = resultingPixel[component] / 255.0f;

    }

    

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值