今天产品经理提出了一个过度透明层的需求,如下图,在此做个笔记以防忘记。
![](https://img.haomeiwen.com/i11093708/9ad413e0ee6b549f.png)
具体实现
CGRect frame = CGRectMake(20, 100, SCREEN_WIDTH-40, SCREEN_HEIGHT-200);
/** 底层的父视图,用来设置透明色的 */
UIView *gradientView = [[UIView alloc] initWithFrame:frame];
gradientView.backgroundColor = [UIColor grayColor];
[self.view addSubview:gradientView];
/** 核心代码,设置逐渐透明色 */
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
NSArray *colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithWhite:0 alpha:0] CGColor], //clearColor,透明度为0(显示为黑色,就像黑洞...)
(id)[[UIColor colorWithWhite:0 alpha:0.5] CGColor],//clearColor,透明度为0.5
(id)[[UIColor colorWithWhite:0 alpha:1] CGColor], //clearColor,透明度为1(显示为透明)
nil];
[gradientLayer setColors:colors];
[gradientLayer setStartPoint:CGPointMake(0.0f, 0.0f)];
[gradientLayer setEndPoint:CGPointMake(0.0f, 0.7f)];/** 设置过度透明层的高度 */
[[gradientView layer] setMask:gradientLayer];
[gradientLayer setFrame:gradientView.bounds];
/** 把想要展示的内容加载到父视图 */
UIScrollView *gradientScrolliew = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
gradientScrolliew.backgroundColor = [UIColor whiteColor];
gradientScrolliew.showsVerticalScrollIndicator = NO;
gradientScrolliew.contentSize = CGSizeMake(SCREEN_WIDTH-40, (SCREEN_HEIGHT-200)*2);
[gradientView addSubview:gradientScrolliew];
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = [self text];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:16];
[gradientScrolliew addSubview:label];
实际上原理就是通过设置父视图的 alpha 透明度,子视图也会随着父视图的 alpha 变化而变化
网友评论