iOS (導航條)navBar 透明


現實開發中會遇到一種情況。UI會把導航條做成透明的,滑動的時候才逐漸顯現。不透明的時候樣子是這樣的。

是挺難看的。

所以想要制作透明的導航條 就要知道一個方法,一個屬性

這時 UIImage 這個圖看來是必須要畫一個了

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *imgae = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imgae;
}

當然也可以給UIImage添加類目

UIImage+colorImge.h

#import <UIKit/UIKit.h>

@interface UIImage (colorImge)
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
@end

UIImage+colorImge.m

#import "UIImage+colorImge.h"

@implementation UIImage (colorImge)

+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGContextAddEllipseInRect(context, rect);
    UIGraphicsEndImageContext();
    return image;
}

@end

這樣就能直接初始化一個UIImage了

這時我們就可以讓導航透明了

 

 

 

 效果如圖

這時想要做到滑動時逐漸變色類似下圖

需要在

- (void)scrollViewDidScroll:(UIScrollView *)scrollView ;方法中做文章了。因為tableVIew繼承自scrollView

在這個方法中判斷tableVIew的contentOffset.y。先看代碼

當前的透明度 = (tableView.contentOffset.y - tableView.contentOffset.y的起點) / (完全不透明的終點 + tableView.contentOffset.y的起點) 一般沒做修改的話 tableView.contentOffset.y的起點是0, 完全不透明的終點 就是看你心情 滑動多遠的時候導航條全變色。

如果有時間的話可以做做封裝。面對多種不同的情況做不同的效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM