在某网站看直播的时候,突然奇想,想自己封装一下弹幕效果,以后做App的时候可以直接用
最终效果:
总结了一下我的需求
1. 界面可显示其他来源的弹幕
2. 要求自己可以发送弹幕
3. 自己发送的弹幕与他人发送的不一致(实现效果与ZQ保持一致)
4. 支持横竖屏切换
5. 承载弹幕的Label要求变长
具体实现
1. 封装一个显示弹幕的Label的生成方法,适用自己发送的信息以及构造的假数据
/**
* 创建界面上显示的弹幕Label
*
* @param titleString 显示的字幕
*/
- (void)createLabelWithTitle:(NSString *)titleString {
NSString *waitDisplayString = titleString;
if (!(titleString && titleString.length != 0)) {
u_int32_t index = arc4random_uniform((u_int32_t)titleArray.count);
waitDisplayString = titleArray[index];
}
// y 坐标
int yPoint = arc4random_uniform(CGRectGetHeight([UIScreen mainScreen].bounds)-45-25)+45;
// 当期弹幕Label的长度
float labelLength = waitDisplayString.length*17;
UILabel *waitDisplayLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth([UIScreen mainScreen].bounds), yPoint, labelLength, 25)];
waitDisplayLabel.text = waitDisplayString;
waitDisplayLabel.backgroundColor = [UIColor clearColor];
waitDisplayLabel.textColor = [self randomColor];
// 若弹幕为自己发送的,将Label的边框显示为白色并且宽带为1
if (titleString && titleString.length != 0) {
waitDisplayLabel.layer.borderColor = [UIColor whiteColor].CGColor;
waitDisplayLabel.layer.borderWidth = 1.0f;
}
[self.view addSubview:waitDisplayLabel];
// 给当前弹幕Label增加向左移动的动画
[self moveAnimation:waitDisplayLabel];
}
2. 当前弹幕移动的动画(要求移动到边缘的时候将其销毁)
/**
* 弹幕Label向左滚动动作
*
* @param waitMoveLabel 待滚动的Label的距离
*/
- (void)moveAnimation:(UILabel *)waitMoveLabel {
[UIView animateWithDuration:4 animations:^{
waitMoveLabel.center = CGPointMake(waitMoveLabel.center.x-CGRectGetMaxX(waitMoveLabel.frame), waitMoveLabel.center.y);
} completion:^(BOOL finished) {
if (finished) {
[waitMoveLabel removeFromSuperview];
}
}];
}
3. 要求能适配横竖屏(Xib或代码)若希望当前界面支持横屏,请将下面的 UIInterfaceOrientationMaskAll 换成 UIInterfaceOrientationMaskLandscape
- (BOOL)shouldAutorotate{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAll;
}
4. 从左向右的滚动效果(NSTimer定时器实现,切记离开界面的时候请将定时器关闭)
- (void)viewDidLoad {
[super viewDidLoad];
titleArray = [NSArray arrayWithObjects:@"你好啊",@"骚年,不错哦",@"啊哈哈",@"O(∩_∩)O哈哈~",@"666666",@"啦啦啦,德玛西亚",@"嗯~你看见我的小熊吗?", nil];
[self.sendCommentButton addTarget:self action:@selector(sendCommentButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
animationTimer = [NSTimer scheduledTimerWithTimeInterval:.3 target:self selector:@selector(addNewCommentToScreen) userInfo:nil repeats:YES];
}
5. 承载弹幕的Label变成,本例是根据字符串的长度进行计算的,有关字符串长度的扩展请看
上述介绍了一下主要技术,相关的实现Demo我已放在 http://download.csdn.net/detail/yanglei3kyou/9066969 供大家下载。封装的如有不满意之处,敬请原谅。