iOS 根据Banner滑动 改变顶部视图颜色

网上搜了有关于iOS根据scrollview滑动值实现导航栏颜色渐变效果但没有搜出相关结果,后面参照了安卓的实现,希望本篇对大家的开发有所帮助。

代码很简单,代码:


+ (NSArray *)getRGBWithColor:(NSString *)color {
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    if (color.length<2) {
        return @[@(253), @(93), @(74)];
    }
    //R、G、B
    NSString *rString = [color substringWithRange:range];
    range.location = 2;
    NSString *gString = [color substringWithRange:range];
    range.location = 4;
    NSString *bString = [color substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return @[@(r), @(g), @(b)];
}

+ (NSArray *)getRGBWithFromColor:(NSString *)fromColor toColor:(NSString *)toColor shade:(CGFloat)mShade {
    NSArray *fromeRgb = [CommonTools getRGBWithColor:fromColor];
    NSArray *toRgb = [CommonTools getRGBWithColor:toColor];

    int fromR = [fromeRgb[0] intValue];
    int fromG = [fromeRgb[1] intValue];
    int fromB = [fromeRgb[2] intValue];
    
    int toR = [toRgb[0] intValue];
    int toG = [toRgb[1] intValue];
    int toB = [toRgb[2] intValue];
    
    int diffR = toR - fromR;
    int diffG = toG - fromG;
    int diffB = toB - fromB;
    
    int red = fromR + (int) ((diffR * mShade));
    int green = fromG + (int) ((diffG * mShade));
    int blue = fromB + (int) ((diffB * mShade));
    
    return @[@(red / 255.0f), @(green / 255.0f), @(blue / 255.0f)];
}

mShade是你的scrollview的滑动值,+ (NSArray)getRGBWithFromColor:(NSString)fromColor toColor:(NSString*)toColor shade:(CGFloat)mShade; 方法得到的是NSNumber类型,需要转成CGFloat类型

        NSArray *rgb = [CommonTools getRGBWithFromColor:self.bgColors[fromIndex] toColor:self.bgColors[toIndex] shade:contentOfSetX/self.cycleScrollView.width];

        CGFloat red = [rgb[0] floatValue];

        CGFloat green = [rgb[1] floatValue];

        CGFloat blue = [rgb[2] floatValue];

        UIColor *bgColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];

    ///改变背景颜色
    if ([self.delegate respondsToSelector:@selector(changeNavBg:)]) {
        [self.delegate changeNavBg:bgColor];
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容