为UIView设置渐变背景

实现方式主要使用了CAGradientLayer。先在ImageView的底端加一个UIView,并在这个UIView上插入一个从透明到黑色的CAGradientLayer,然后再UIView上插入一个Label就行了。

实现代码如下:

import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
CAGradientLayer *_gradientLayer;
UIView *_layerView;
UIImageView *_imageView;
}

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor blueColor];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 350, 150, 100)];
    [button setTitle:@"显示/隐藏标题" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test"]];
    _imageView.frame = CGRectMake(0, 0, 320, 320);

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 320, 100)];
    label.text = @"我是标题标题标题!";
    label.textColor = [UIColor whiteColor];

    _layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 320-100, 320, 100)];

    _gradientLayer = [CAGradientLayer layer]; // 设置渐变效果
    _gradientLayer.bounds = _layerView.bounds;
    _gradientLayer.borderWidth = 0;

    _gradientLayer.frame = _layerView.bounds;
    _gradientLayer.colors = [NSArray arrayWithObjects:
    (id)[[UIColor clearColor] CGColor],
    (id)[[UIColor blackColor] CGColor], nil nil];
    _gradientLayer.startPoint = CGPointMake(0.5, 0.5);
    _gradientLayer.endPoint = CGPointMake(0.5, 1.0);

    [_layerView.layer insertSublayer:_gradientLayer atIndex:0];

    [_imageView addSubview:_layerView];
    [_layerView addSubview:label];
    [self.view addSubview:_imageView];
    }

  • (void)buttonPressed
    {
    static BOOL yesOrNo = YES;
    if (yesOrNo) {
    [_layerView removeFromSuperview];
    } else {
    [_imageView addSubview:_layerView];
    }
    yesOrNo = !yesOrNo;

}

@end

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

相关阅读更多精彩内容

  • //设置尺寸为屏幕尺寸的时候self.window = [[UIWindow alloc] initWithFra...
    LuckTime阅读 4,318评论 0 0
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 4,819评论 1 6
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 7,359评论 1 14
  • 闲来柳下坐观棋,非己输赢也喜悲。 一着轻心丢好局,几回得意出奇时。 英伦烟雨笼欧暗,半岛风云阻核迟。 为问谁如枰上...
    乱蝉嘶暮阅读 4,390评论 6 8
  • 坚持分享第32天 今天下午,因为妈妈有事,所以我和爸爸替妈妈看车,我在车里,爸爸去转了一圈,我忽然唱起父亲这首歌唱...
    分享坚持大师阅读 1,418评论 1 3

友情链接更多精彩内容