隨筆待整理
#import "UINavigationBar+ChangeColor.h"
@implementation UINavigationBar (ChangeColor)
- (void)start{
UIImageView *shawImage = [self findNavLineImageOn:self];
shawImage.hidden = YES;
self.translucent = YES;
}
- (void)reset{
UIImageView *shawImage = [self findNavLineImageOn:self];
shawImage.hidden = NO;
[self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
self.translucent = NO;
}
- (void)changeColor:(UIColor *)color withScrollView:(UIScrollView *)scrollView andValud:(CGFloat)value{
if (scrollView.contentOffset.y < 0) {
//下拉時導航隱藏
self.hidden = YES;
}else{
self.hidden = NO;
//計算透明度
CGFloat alpha = scrollView.contentOffset.y /value > 1.0f ? 1 : scrollView.contentOffset.y/value;
//設置顏色改為圖片
UIImage *image = [self imageWithColor:[color colorWithAlphaComponent:alpha]];
[self setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
self.translucent = alpha >=1.0f ? NO : YES;
}
}
- (UIImageView *)findNavLineImageOn:(UIView *)imageView{
if ([imageView isKindOfClass:[UIImageView class]] && imageView.frame.size.height <=1.0) {
return (UIImageView *)imageView;
}
for (UIView *subViews in imageView.subviews) {
UIImageView *imageView = [self findNavLineImageOn:subViews];
if (imageView) {
return imageView;
}
}
return nil;
}
#pragma mark - Color To Image
- (UIImage *)imageWithColor:(UIColor *)color {
//創建1像素區域並開始圖片繪圖
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
//創建畫板並填充顏色和區域
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
//從畫板上獲取圖片並關閉圖片繪圖
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
隨筆待整理