设置需要UILabel的字体、文本内容与颜色数组后,调用setGradientLabel方法即可显示
GradientLabel.h
#import <UIKit/UIKit.h>
@interface GradientLabel : UIView
@property (nonatomic, strong) NSArray * colors;//字体渐变颜色数组(必须将颜色转换为CGColor并强制转换为id类型)
@property (nonatomic, strong) UIFont *font;//字体
@property (nonatomic, copy) NSString *text;//设置渐变颜色的文字
@property (nonatomic, assign) NSTextAlignment textAlignment;//对齐方式
@property (nonatomic, assign) CGPoint startPoint;//起始点(0.0~1.0)
@property (nonatomic, assign) CGPoint endPoint;//结束点(0.0~1.0)
//应用设置
- (void) setGradientLabel;
@end
GradientLabel.m
#import "GradientLabel.h"
@interface GradientLabel ()
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@end
@implementation GradientLabel
- (CAGradientLayer *)gradientLayer {
if (!_gradientLayer) {
_gradientLayer = [CAGradientLayer layer];
_gradientLayer.startPoint = CGPointMake(0.0,1.0);
_gradientLayer.endPoint = CGPointMake(1.0, 1.0);
_gradientLayer.frame = self.label.frame;
_gradientLayer.colors = self.colors?:@[[UIColor whiteColor], [UIColor blackColor]];
}
return _gradientLayer;
}
- (void) setGradientLabel {
self.label = [[UILabel alloc] init];
self.label.text = self.text?:@"渐变字体";
[self.label setFont:self.font?:[UIFont systemFontOfSize:13]];
[self.label setTextAlignment:self.textAlignment?:kCTLeftTextAlignment];
[self addSubview:self.label];
}
-(void)layoutSubviews {
[super layoutSubviews];
[self.label setFrame:self.bounds];
// 添加渐变层到控制器的view图层上
if (self.gradientLayer.superlayer == nil) {
[self.layer addSublayer:self.gradientLayer];
// mask层工作原理:按照透明度裁剪,只保留非透明部分,文字就是非透明的,因此除了文字,其他都被裁剪掉,这样就只会显示文字下面渐变层的内容,相当于留了文字的区域,让渐变层去填充文字的颜色。
// 设置渐变层的裁剪层
self.gradientLayer.mask = self.label.layer;
}
}
@end
网友评论