项目需要,需要在图片上显示文字,但是文字的颜色很难控制,有时候与背景图的颜色很接近导致文字难以看清楚,可以通过将图片上显示文字的地方加一层黑色的半透明的背景色来解决这个问题。将这层背景色做成从黑色到透明的渐变。
比如这样一张图,我需要在低端加上介绍文字
可以看到底下变得更黑了,文字更加清楚。
实现方式主要使用了CAGradientLayer。先在ImageView的底端加一个UIView,并在这个UIView上插入一个从透明到黑色的CAGradientLayer,然后再UIView上插入一个Label就行了。
实现代码如下:
//
// ViewController.m
// Layer
//
// Created by xuzhaocheng on 14-6-17.
// Copyright (c) 2014年 Zhejiang University. All rights reserved.
//
-
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