自定义文本横向渐变消失的控件

来源:互联网 发布:剑三霸刀萝莉捏脸数据 编辑:程序博客网 时间:2024/05/01 19:13

自定义文本横向渐变消失的控件

.h文件内容

#import <UIKit/UIKit.h>@interface FadeStringView : UIView/** *  输入文本 */@property (strong, nonatomic) NSString *text;/** *  @brief  向右渐变消失 */- (void)fadeRight;//最好这样子实现- (void)fadeRightWithDuration:(NSTimeInterval)duration animated:(BOOL)animated;@end

.m文件内容

#import "FadeStringView.h"@interface FadeStringView ()@property (strong, nonatomic) UILabel *label;@property (strong, nonatomic) UIView *mask;//作为遮罩的mask@end@implementation FadeStringView- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        //创建label        [self createLabel:frame];        //创建出mask        [self createMask:self.bounds];    }    return self;}- (void)createLabel:(CGRect)frame{    self.label              = [[UILabel alloc] initWithFrame:frame];    self.label.font         = [UIFont systemFontOfSize:30.f];    self.label.textAlignment = NSTextAlignmentCenter;    [self addSubview:self.label];}-(void)createMask:(CGRect)frame{    CAGradientLayer *gradientLayer = [CAGradientLayer layer];    gradientLayer.frame = frame;    gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor,                             (__bridge id)[UIColor blackColor].CGColor,                             (__bridge id)[UIColor blackColor].CGColor,                             (__bridge id)[UIColor clearColor].CGColor];    gradientLayer.locations = @[@(0.01),@(0.1),@(0.9),@(0.99)];    gradientLayer.startPoint = CGPointMake(0, 0);    gradientLayer.endPoint = CGPointMake(1, 0);    //创建并接管mask    self.mask = [[UIView alloc] initWithFrame:frame];    //将渐变图层加到mask图层上作为子图层    [self.mask.layer  addSublayer:gradientLayer];    self.maskView = self.mask;}/** *  @brief  向右渐变消失 */- (void)fadeRight{    [UIView animateWithDuration:3.f animations:^{        CGRect frame = self.mask.frame;        frame.origin.x += frame.size.width;        self.mask.frame = frame;    }];}/** *  重写setter/getter 方法 */@synthesize text = _text;- (void)setText:(NSString *)text{    _text = text;    self.label.text = text;}-(NSString *)text{    return _text;}@end

viewController里调用函数如下

#import "FadeStringView.h" FadeStringView *fadeStringView = [[FadeStringView alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];    fadeStringView.center = self.view.center;    fadeStringView.text = @"iOS开发测试用例";    [self.view addSubview:fadeStringView];    [fadeStringView fadeRight];
0 0
原创粉丝点击