相信大家有时候会遇到在首页上部展示一行文字,但是文字又很长无法只使用一行来展示,于是大家就想到平时我们在生活中看到的LED屏幕那样滚动展示完整的一句话语,今天写的这个控件就是实现了这样一个效果.
1.在进入正文之前,我们先来了解一下layer的mask层.
mask层其实就是一个遮罩layer,有点类似于我们平常弹出键盘时一并出来的灰色蒙层,只不过mask层是一个layer,而和键盘一并弹出来的大多设置的是一个改变透明度后的view.
CAShapeLayer* maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
self.view.layer.mask = maskLayer;
这三句代码就是设置一个view的mask蒙层让处于view外部的内部不被显示出来,这次封装的lable主要就是用到这个原理.
2.接下来我们就开始进行封装
一般滚动的话我们肯定会想要通过对外的接口来改变滚动的速度,因此首先我们自定义一个view,声明一个对外的接口,如:
-(id)initWithFrame:(CGRect)frame Text:(NSString *)textStr TextColor:(UIColor *)textColor BackGroundColor:(UIColor *)backColor Speed:(CGFloat)speed ;
下面我们来实现这个方法
-(id)initWithFrame:(CGRect)frame Text:(NSString *)textStr TextColor:(UIColor *)textColor BackGroundColor:(UIColor *)backColor Speed:(CGFloat)speed{
self = [super initWithFrame:frame];
if (self) {
//取出对外接口中的颜色等值并赋值给自定义view声明的私有变量,方便UI的更新
self.textColor = textColor;
self.backGroundColor = backColor;
self.speed = speed;
self.textStr = textStr;
[self creatUI];
}
return self;
}
-(void)creatUI{
self.backgroundColor = _backGroundColor;
self.annimationLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
_annimationLabel.textColor = _textColor;
_annimationLabel.backgroundColor = [UIColor clearColor];
_annimationLabel.text = _textStr;
[_annimationLabel sizeToFit];
[self addSubview:_annimationLabel];
//添加mask
//给bgview添加一个layer蒙层,使bgview上label暴露在bgview外部的字不再显现出来(因为label设置的是sizeToFit,所以label的宽度会根据字符串的长度来调整,若不设此蒙层还是会显现出来,达不到移动的效果);
CAShapeLayer* maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
self.layer.mask = maskLayer;
[self addAnimationToLabel];
}
-(void)addAnimationToLabel{
[_annimationLabel.layer removeAllAnimations];
CGFloat space = _annimationLabel.frame.size.width - self.frame.size.width;
CAKeyframeAnimation* keyFrame = [CAKeyframeAnimation animation];
keyFrame.keyPath = @"transform.translation.x";
keyFrame.values = @[@(0), @(-space), @(0)];
keyFrame.repeatCount = INT16_MAX;
keyFrame.duration = _speed * _annimationLabel.text.length;
keyFrame.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut], [CAMediaTimingFunction functionWithControlPoints:0 :0 :0.5 :0.5]];
[_annimationLabel.layer addAnimation:keyFrame forKey:nil];
}
这样就完成了封装,我封装的文件名为AnimationLabel,因此在控制器中使用时:
UIColor *color = [UIColor magentaColor];
UIColor *bgColor = [UIColor lightGrayColor];
AnimationLabel *label = [[AnimationLabel alloc]initWithFrame:CGRectMake(50, 100, 150, 50) Text:@"大猴子小猴子,大小猴子,小大猴子,子猴大小,猴子小大" TextColor:color BackGroundColor:bgColor Speed:0.6];
[self.view addSubview:label];
网友评论