UIView渐变背景

项目需要,需要在图片上显示文字,但是文字的颜色很难控制,有时候与背景图的颜色很接近导致文字难以看清楚,可以通过将图片上显示文字的地方加一层黑色的半透明的背景色来解决这个问题。将这层背景色做成从黑色到透明的渐变。

UIView渐变背景_第1张图片
image.png

比如这样一张图,我需要在低端加上介绍文字

UIView渐变背景_第2张图片
image.png

可以看到底下变得更黑了,文字更加清楚。

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

实现代码如下:

  1. //

  2. // ViewController.m

  3. // Layer

  4. //

  5. // Created by xuzhaocheng on 14-6-17.

  6. // Copyright (c) 2014年 Zhejiang University. All rights reserved.

  7. //

  8. import "ViewController.h"

  9. @interface ViewController ()

  10. @end

  11. @implementation ViewController

  12. {

  13. CAGradientLayer *_gradientLayer;

  14. UIView *_layerView;

  15. UIImageView *_imageView;

  16. }

    • (void)viewDidLoad
  17. {

  18. [super viewDidLoad];

  19. // Do any additional setup after loading the view, typically from a nib.

  20. self.view.backgroundColor = [UIColor blueColor];

  21. UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 350, 150, 100)];

  22. [button setTitle:@"显示/隐藏标题" forState:UIControlStateNormal];

  23. [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

  24. [self.view addSubview:button];

  25. _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test"]];

  26. _imageView.frame = CGRectMake(0, 0, 320, 320);

  27. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 320, 100)];

  28. label.text = @"我是标题标题标题!";

  29. label.textColor = [UIColor whiteColor];

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

  31. _gradientLayer = [CAGradientLayer layer]; // 设置渐变效果

  32. _gradientLayer.bounds = _layerView.bounds;

  33. _gradientLayer.borderWidth = 0;

  34. _gradientLayer.frame = _layerView.bounds;

  35. _gradientLayer.colors = [NSArray arrayWithObjects:

  36. (id)[[UIColor clearColor] CGColor],

  37. (id)[[UIColor blackColor] CGColor], nil nil];

  38. _gradientLayer.startPoint = CGPointMake(0.5, 0.5);

  39. _gradientLayer.endPoint = CGPointMake(0.5, 1.0);

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

  41. [_imageView addSubview:_layerView];

  42. [_layerView addSubview:label];

  43. [self.view addSubview:_imageView];

  44. }

    • (void)buttonPressed
  45. {

  46. static BOOL yesOrNo = YES;

  47. if (yesOrNo) {

  48. [_layerView removeFromSuperview];

  49. } else {

  50. [_imageView addSubview:_layerView];

  51. }

  52. yesOrNo = !yesOrNo;

  53. }

  54. @end

你可能感兴趣的:(UIView渐变背景)