UILabel 設定漸變顏色字型
/*
設定需要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
@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"
@interfaceGradientLabel
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
@end
@implementation GradientLabel
- (CAGradientLayer *)gradientLayer {
if (!_gradientLayer) {
_gradientLayer = [CAGradientLayerlayer];
_gradientLayer.startPoint = CGPointMake(0.0,1.0);
_gradientLayer
_gradientLayer.frame = self.label.frame;
_gradientLayer.colors = self.colors?:@[[UIColorwhiteColor], [UIColorblackColor]];
}
return_gradientLayer;
}
- (void) setGradientLabel {
self.label = [[UILabelalloc] init];
self.label.text = self.text?:@"漸變字型";
[self.labelsetFont:self.font?:[UIFontsystemFontOfSize:13]];
[self.labelsetTextAlignment:self.textAlignment?:kCTLeftTextAlignment];
[selfaddSubview:self.label];
}
-(void)layoutSubviews {
[superlayoutSubviews];
[self.labelsetFrame:self.bounds];
// 新增漸變層到控制器的view圖層上
[self.layeraddSublayer:self.gradientLayer];
// mask層工作原理:按照透明度裁剪,只保留非透明部分,文字就是非透明的,因此除了文字,其他都被裁剪掉,這樣就只會顯示文字下面漸變層的內容,相當於留了文字的區域,讓漸變層去填充文字的顏色。
// 設定漸變層的裁剪層
self.gradientLayer.mask = self.label.layer;
}
@end
程式碼地址:https://github.com/15736882551/GCGradientLabel