iOS 滚动过程中逐渐切换颜色值

//fromColor开始滚动切换前的颜色(十六进制)
//滚动切换结束后的颜色toColor(十六进制)
//ratio滚动比例(向左滚动逐渐变大)

+ (UIColor *) loadFromColor:(NSString *)fromColor toColor:(NSString *)toColor andRatio:(CGFloat)ratio
{
     if (fromColor == nil && toColor == nil) {
          return nil;
     }
     //滚动切换前颜色
    if (![fromColor containsString:@"#"]) {
         fromColor = [NSString stringWithFormat:@"#%@", fromColor];
    }
    unsigned int fromRed, fromGreen, fromBlue;
    NSRange fromRange;
     fromRange.length = 2;
     fromRange.location = 1;
    [[NSScanner scannerWithString:[fromColor substringWithRange:fromRange]] scanHexInt:&fromRed];
     fromRange.location = 3;
    [[NSScanner scannerWithString:[fromColor substringWithRange:fromRange]] scanHexInt:&fromGreen];
     fromRange.location = 5;
    [[NSScanner scannerWithString:[fromColor substringWithRange:fromRange]] scanHexInt:&fromBlue];

     //滚动切换后颜色
     if (toColor == nil) {
         return nil;
     }
     if (![toColor containsString:@"#"]) {
          toColor = [NSString stringWithFormat:@"#%@", toColor];
     }
     unsigned int toRed, toGreen, toBlue;
     NSRange toRange;
     toRange.length = 2;
     toRange.location = 1;
     [[NSScanner scannerWithString:[toColor substringWithRange:toRange]] scanHexInt:&toRed];
     toRange.location = 3;
     [[NSScanner scannerWithString:[toColor substringWithRange:toRange]] scanHexInt:&toGreen];
     toRange.location = 5;
     [[NSScanner scannerWithString:[toColor substringWithRange:toRange]] scanHexInt:&toBlue];
     
     //渐变颜色
     CGFloat lastRed, lastGreen, lastBlue;
     //处理红色
     //100 ----> 30
     if(fromRed >= toRed){
          lastRed = fromRed - (fromRed - toRed)*ratio;
     } else {
          lastRed = fromRed + (toRed - fromRed)*ratio;
     }
     //处理绿色
     if(fromGreen >= toGreen){
          lastGreen = fromGreen - (fromGreen - toGreen)*ratio;
     } else {
          lastGreen = fromGreen + (toGreen - fromGreen)*ratio;
     }
     //处理蓝色
     if(fromBlue >= toBlue){
          lastBlue = fromBlue - (fromBlue - toBlue)*ratio;
     } else {
          lastBlue = fromBlue + (toBlue - fromBlue)*ratio;
     }
     return [UIColor colorWithRed:(float)(lastRed/255.0f) green:(float)(lastGreen/255.0f) blue:(float)(lastBlue/255.0f) alpha:1.0f];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容