美文网首页
iOS 根据Banner滑动 改变顶部视图颜色

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

作者: 蛋上有皱纹 | 来源:发表于2022-11-21 10:48 被阅读0次

    网上搜了有关于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];
        }

    相关文章

      网友评论

          本文标题:iOS 根据Banner滑动 改变顶部视图颜色

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