一个简单的弹幕效果

                             一个简单的弹幕效果

      说到斗鱼,很多盆友肯定都知道,作为一名斗鱼的忠实用户。对斗鱼的弹幕效果是再熟悉不过了,最近自己动手写了一个demo,效果一般,大家就看看吧。

好了,废话不多说,直接上代码。

#import "ViewController.h"

#define screenW    [UIScreen mainScreen].bounds.size.width

#define textHeight  40

#define textFont    14.f

@interface ViewController (){

NSInteger _index;

CGFloat _font;

}

@property (nonatomic,strong) NSArray *titleArray;

@end

@implementation ViewController

- (NSArray *)titleArray

{

if (_titleArray == nil) {

NSString *path = [[NSBundle mainBundle] pathForResource:@"danmu.plist" ofType:nil];

_titleArray = [NSArray arrayWithContentsOfFile:path];

}

return _titleArray;

}

/**

随机颜色

随机高度

运行循环

创建label方法

动态计算label的宽高

*/

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor = [UIColor lightGrayColor];

_index = 0;

// 时间直接加入到运行循环

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(setUpTitleLabel) userInfo:nil repeats:YES];

}

-(void)setUpTitleLabel

{

_index ++;

if (_index == self.titleArray.count) {

_index = 0;

}

NSString *title = self.titleArray[_index];

UILabel *textLabel = [[UILabel alloc] init];

textLabel.text = title;

//    textLabel.frame = [self textLabelWithString:title];

接上面

// 全局记录当前文字大小

_font = [self arc4randomFont];

textLabel.font = [UIFont systemFontOfSize:_font];

[self.view addSubview:textLabel];

textLabel.textColor = [self arc4randomColor];

// label高度

CGFloat labelY = [self arc4randomY];

textLabel.frame = CGRectMake(screenW, labelY, [self textLabelWithString:title].width, textFont);

// 从右到左

[UIView animateWithDuration:3 animations:^{

textLabel.frame = CGRectMake(-[self textLabelWithString:title].width, labelY, [self textLabelWithString:title].width, textFont);

}completion:^(BOOL finished) {

[textLabel removeFromSuperview];

}];

}

#pragma mark - 计算文本宽高方法

-(CGSize)textLabelWithString:(NSString *)string

{

return [string boundingRectWithSize:CGSizeMake(MAXFLOAT, textHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_font]} context:nil].size;

}

#pragma mark - 随机颜色

-(UIColor *)arc4randomColor

{

return [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1];

}

#pragma mark - 随机高度

-(CGFloat)arc4randomY

{

CGFloat textY = [UIScreen mainScreen].bounds.size.height * 0.5;

return arc4random_uniform(textY);

}

#pragma mark - 随机文字大小

-(CGFloat)arc4randomFont

{

return  arc4random_uniform(8) + 13;

}

@end

     基本弹幕效果实现了,但是应该还有更简单的方法,欢迎大家批评指证。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容