//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];
}
网友评论