现在很多的视频播放客户端都支持弹幕功能,用户玩起来会感觉非常好玩。其实弹幕集成起来非常简单,无非就是把一些评论添加到UILabel上,然后从右往左移动即可,实现起来其实非常简单。

我们把他封装成一个UIView的子类,起名为BarrageView , 然后添加一个评论数组的属性:CommentArray 。还需要暴露出两个方法,打开弹幕:openBarrage,添加自己的评论:addMyComment:。大家去弹幕网站就应该会注意到,别人的评论一般是白色的,而当我们输入自己评论,然后显示的时候,网站会把我们的评论设置成彩色的以便与别人区分。所以,加一个输入自己评论的方法,我们会把评论内容生成NSMutableAttributedString。这种字符串可以存储字体颜色、大小等属性,方便我们统一修改和操作。

代码如下所示:

#import <UIKit/UIKit.h>@interface BarrageView : UIView@property (nonatomic, strong) NSMutableArray *commentArray;//开启弹幕
-(void)openBarrage;//自己评论内容,颜色彩色
-(void)addMyComment:(NSString *)comment;
@end

用户传进来的是一个普通的commentArray,我们需要做一下转换,把所有的NSString 转换成NSMutableAttributedString,然后添加到一个数组当中。新建一个数组

@property (nonatomic, strong) NSMutableArray *attributedCommentArray;
接下来转换:

for(NSString *string in self.commentArray){NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:string];[attributedStr addAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor] ,NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]} range:NSMakeRange(0, string.length)];[self.attributedCommentArray addObject:attributedStr];        }

我们把字体颜色设置成白色,字号大小设置为15。

加一个定时器,每0.3秒生成一个UILabel,从右面往左移动
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(createLabel) userInfo:nil repeats:YES];

接下来就是创建UILabel了,每个label应该能自适应宽度,也就是每个label的宽度应该根据评论内容的宽度动态改变。 先给label.attributedText赋值。然后,根据attributes计算出评论内容的CGSize,以这个size重新给label的frame 赋值。

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];[self addSubview:label];NSMutableAttributedString *textObject = [self.attributedCommentArray lastObject];label.attributedText = textObject;[self.attributedCommentArray removeLastObject];[self.attributedCommentArray insertObject:textObject atIndex:0];CGSize size = [label.attributedText.string sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]}];CGFloat windowHeight = self.frame.size.height;CGFloat windowWidth = self.frame.size.width;CGFloat yPosition = arc4random()%(((int)windowHeight)/20) * 20.0; CGRect frame = CGRectMake(windowWidth, yPosition, size.width, size.height);label.frame = frame;

需要注意的是:每个label的初始位置x是固定的,但是y的位置是要随机生成的,我们让每个label占用20的高度,然后用整个BarrageView的高度/20 就是每个view在y轴上容纳的 label个数:count,然后随机出 一个整数,范围在 0~ count-1。然后用count * 20 就是lable的随机y轴位置了。

最后给label添加动画,从右往左移动:

-(void)animationWithView:(UIView *)view
{int random = arc4random()%6;CGFloat duration = random + 3.0;CGPoint endPoint = CGPointMake(0 - view.frame.size.width, view.frame.origin.y);CGRect endRect = CGRectMake(endPoint.x, endPoint.y, view.frame.size.width, view.frame.size.height);[UIView animateWithDuration:duration animations:^{//[self translationToLeftWithView:view];[UIView setAnimationCurve:UIViewAnimationCurveLinear];[view setFrame:endRect];} completion:^(BOOL finished) {[view removeFromSuperview];}];}

没个label动画结束后,要销毁,不然会引起内存泄露,最后。labe调用上述方法,完成动画.
[self animationWithView:label];

下面是完整的实现代码:

//
//  BarrageView.h
//  BarrageTest
//
//  Created by victor on 9/8/15.
//  Copyright © 2015 vcitor. All rights reserved.
//#import "BarrageView.h"@interface BarrageView()@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSMutableArray *attributedCommentArray;@end@implementation BarrageView- (instancetype)init
{self = [super init];if (self) {self.attributedCommentArray = [NSMutableArray new];}return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{self = [super initWithFrame:frame];if (self) {self.attributedCommentArray = [NSMutableArray new];}return self;
}
-(void)openBarrage
{if (self.timer) {[self.timer invalidate];self.timer = nil;}for(NSString *string in self.commentArray){NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:string];[attributedStr addAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor] ,NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]} range:NSMakeRange(0, string.length)];[self.attributedCommentArray addObject:attributedStr];}[self initLayer];
}-(void)addMyComment:(NSString *)comment
{NSMutableAttributedString *attrComment = [[NSMutableAttributedString alloc] initWithString:comment];[attrComment addAttributes:@{NSForegroundColorAttributeName: [UIColor greenColor], NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]} range:NSMakeRange(0, comment.length)];[self.attributedCommentArray addObject:attrComment];
}-(void)closeBarrage
{if (self.timer) {[self.timer invalidate];self.timer = nil;[self.attributedCommentArray removeAllObjects];}for(UIView *view in self.subviews){[view removeFromSuperview];}
}-(void)initLayer
{self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(createLabel) userInfo:nil repeats:YES];
}-(void)createLabel
{UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];NSMutableAttributedString *textObject = [self.attributedCommentArray lastObject];label.attributedText = textObject;[self.attributedCommentArray removeLastObject];[self.attributedCommentArray insertObject:textObject atIndex:0];[self addSubview:label];CGSize size = [label.attributedText.string sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15.0f]}];CGFloat windowHeight = self.frame.size.height;CGFloat windowWidth = self.frame.size.width;CGFloat yPosition = arc4random()%(((int)windowHeight)/20) * 20.0;CGRect frame = CGRectMake(windowWidth, yPosition, size.width, size.height);label.frame = frame;[self animationWithView:label];}-(void)animationWithView:(UIView *)view
{int random = arc4random()%6;CGFloat duration = random + 3.0;CGPoint endPoint = CGPointMake(0 - view.frame.size.width, view.frame.origin.y);CGRect endRect = CGRectMake(endPoint.x, endPoint.y, view.frame.size.width, view.frame.size.height);[UIView animateWithDuration:duration animations:^{//[self translationToLeftWithView:view];[UIView setAnimationCurve:UIViewAnimationCurveLinear];[view setFrame:endRect];} completion:^(BOOL finished) {[view removeFromSuperview];}];}
-(void)dealloc
{[self.timer invalidate];self.timer = nil;
}
@end

把BarrageView头文件引入你的ViewController当中:并初始化,赋值评论数组,openBarrage即可完成添加。
下面是代码示例:

 self.view.backgroundColor = [UIColor lightGrayColor];_barrageView = [[BarrageView alloc]initWithFrame:self.view.bounds];[self.view addSubview:_barrageView];_barrageView.commentArray = [NSMutableArray arrayWithObjects:@"关弹幕 保智商",@"我不服",@"我的鱼丸呢我擦", @"摄像头挡住了",@"23333333333",@"6666666666",@"这波不亏",@"实力3杀",@"瑞文能打得过剑姬?",@"草",@"我赵日天不服",@"666666666",@"1111111",@"不要怂就是干啊",@"补刀好吊", nil];self.textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 150, 200, 30)];self.textField.backgroundColor = [UIColor whiteColor];self.textField.placeholder = @"输入评论";[self.view addSubview:self.textField];UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeSystem];startBtn.frame = CGRectMake(100, 200, 100, 30);[startBtn setTitle:@"添加评论" forState:UIControlStateNormal];[startBtn addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:startBtn];[self.barrageView openBarrage];


从Demo截图中可以看出,自己输入的评论是彩色的和别人区分。
源码可在这里下载

iOS 播放器 或直播添加 弹幕相关推荐

  1. MFC+DuiVision结合VLC播放器开发直播客户端

    MFC+DuiVision结合VLC播放器开发直播客户端 说明:windows 10 VS2015社区版 关键字:c++ VisualStudio DuiVision VLC播放器 开发这个视频播放器 ...

  2. 播放器、直播平台、OBS相关测试

    功能测试 前后端分离情况下,视频资源是否可以正常获取,不管是服务器返回还是后台添加等 打开.关闭播放器 播放.暂停.停止播放器 拖动进度条查看是否卡顿 是否支持所有格式的文件?多个格式的文件进行测试 ...

  3. wap html5播放器和直播开发小结

    此文已由作者吴家联授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 去年年中的时候,借着产品改版的机会,将之前的h5播放器好好整理重构了一番.之前的h5播放器较为简陋,有几个大 ...

  4. 斗鱼 html播放器,斗鱼直播平台简易播放器 v1.2 (20180223更新)

    importwin.ui;/*DSG{{*/varwinform = win.form(text="斗鱼简易播放器";right=935;bottom=607) winform.a ...

  5. 视频云:点播播放器和直播播放器冲突如何解决?

    1.问题 开发者有点播和直播都需要用,既有播放网络视频的需求也有直播播放视频流的需求,这个时候如果用户先集成了点播播放器再去集成直播播放器的时候会出现冲突报错. 2.解决方案 开发者仅仅使用直播播放器 ...

  6. 8K播放网络全终端播放器H5播放器网页直播/点播播放器EasyPlayer和vlc播放RTSP流地址不兼容问题排查解决

    背景介绍 EasyPlayer实现了对遵循标准流媒体码流协议进行实时播放以及码流录制,在流的播放速度以及画质的解码显示上均做了大量深度的优化.支持Windows(支持多窗口.包含ActiveX,npA ...

  7. 在网站上的视频直播添加弹幕做法

    弹幕使用的是阿里云的Aliplayer 参考官网:https://help.aliyun.com/document_detail/125570.html?spm=a2c4g.11186623.6.10 ...

  8. html中加入音乐播放器,HTML网页添加音乐播放器做背景音乐代码-标签audio

    是 HTML 5 的一个新标签,定义声音,比如音乐或其他音频流. 调用格式: src="http://sc1.111ttt.com/2016/1/02/04/195040016323.mp3 ...

  9. iOS播放器 - AVPlayer

    之前有说到在播放器中一点点小技巧,现在正式记录一下AVPlayer. 这里主要是说明用AVPlayer做音乐播放器的功能实现,所以不介绍AVPlayer中那个图层类. 首先我们要声明一下播放器,这里有 ...

最新文章

  1. 示波器输入阻抗匹配问题
  2. Ubuntu 18.04 忘记 mysql root密码及其重置
  3. 深度强化学习:如何在AI工程实践中选择合适的算法?
  4. 浙大版python_浙大版《Python 程序设计》题目集1-5
  5. 目不给视的拼音及解释
  6. ELK结合Beats工具的搭建使用(Metricbeat、Filebeat、Topbeat)
  7. 区分execl与system——应用程序中执行命令
  8. JVM(十),垃圾回收之新生代垃圾收集器
  9. 临危不惧和力记易让容灾也有真本事
  10. 计算机考研各省份学校,想考研究生,哪个省份的高校更容易考上?
  11. 体脂率在线计算机,体脂率(BFR)计算器
  12. 串行通讯控制器8250
  13. 互联网日报 | 1月10日 星期日 | 小米之家千店同开;蔚来发布首款旗舰轿车ET7;LVMH完成收购Tiffany...
  14. 计算机连接未识别的网络,电脑网络连接出现未识别的网络怎么办
  15. 用WORD制表的一些技巧
  16. Git使用技巧--详细教程
  17. 遇人不淑之逗比程序员
  18. Blender导出模型规范检查
  19. Android——App版本控制PHP
  20. java线程状态管理

热门文章

  1. 廖雪峰讲python高阶函数求导_高阶函数 · 廖雪峰的Python3.x教程 · 看云
  2. GBase项目管理实践总结-里程碑管理
  3. 程序员面试金典(C++)——确定字符互异
  4. 使用 Multiprocessing.Pool.map_async 报错 attribute lookup <lambda> on __main__ failed 的解决
  5. 数学建模——存贮模型
  6. 计算机地图综合制图实验报告,ArcMap制图-地图版面设计实验报告.doc
  7. SurfaceView使用方法简介-来自网络
  8. 计算机毕设源码网站基于SpringBoot的阳光线上交友系统
  9. java-API 全——超过4000行
  10. Ubuntu下FastDFS的安装