某天,偶然打开了QQ音乐,又偶然打开了它的弹幕,闲着没事就搜索了一下别人的代码,发现都不是特别还原,于是就。。。
1.先看效果
-
效果(一)
-
效果(二)
2.弹幕消息处理
// 收到一条弹幕消息
- (void)receivedMessage:(DHBarrageMessage *)message {
NSInteger iIndex = [self iIndex];
if (iIndex == -1) {
/// 通道满了就移除第一条弹幕 -> 消息队列添加 -> 一条消息 -> cell缓存队列移除最后一个 -> 开启定时器检测 -> 等待通道释放 -> 更新
[self.subviews.firstObject removeFromSuperview];
[_barrageMessages addObject:message];
[_barrageCells removeLastObject];
if (!_timer) {
_timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
[_timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
} else {
/// 有空余通道直接显示
[self showBarrageCellWithBarrageMessage:message idleIndex:iIndex];
}
}
3.弹幕显示
// 显示弹幕消息
- (void)showBarrageCellWithBarrageMessage:(DHBarrageMessage *)message iIndex:(NSInteger)iIndex {
if (!_cellClass) {
_cellClass = [DHBarrageViewCell class];
}
DHBarrageChannel *channel = _channels[iIndex]; // 获取通道
DHBarrageViewCell *cell = [[_cellClass alloc] initWithFrame:CGRectMake(0, 0, 0, _channelHeight)];
[cell setValue:message forKey:@"message"];
cell.frame = ({
CGRect frame = cell.frame;
frame.size.width = [cell setupSubviews:iIndex];
frame.origin.x = 0;
frame.origin.y = self.frame.size.height-(_channelHeight+_lineSpacing);
frame.size.height = _channelHeight;
frame;
});
[self addSubview:cell];
[channel.cells addObject:cell];
channel.lastCell = cell;
[_barrageCells insertObject:cell atIndex:0];
cell.layer.anchorPoint = CGPointMake(0, 1);
[self.layer addSublayer:cell.layer];
// 创建组动画
CAAnimation *animScale = [CAAnimationTool scaleAnimationFromValue:0 toValue:1.f duration:0.3];
CAAnimation *opacity = [CAAnimationTool opacityAnimationFromValue:0 toValue:1.f duration:0.3];
CAAnimation *animx = [CAAnimationTool positionXAnimationFromValue:0 toValue:10 duration:0.3];
CAAnimation *animy = [CAAnimationTool positionYAnimationFromValue:self.frame.size.height toValue:self.frame.size.height-_channelHeight-_lineSpacing - _channelHeight/2 duration:0.3];
CAAnimationGroup *group = [[CAAnimationGroup alloc] init];
group.animations = @[animScale,opacity,animx,animy];
group.duration = 1.0;
group.removedOnCompletion = NO;
group.fillMode = kCAFillModeForwards;
group.delegate = self;
[cell.layer addAnimation:group forKey:nil];
}
随便贴了点核心代码 源码DEMO地址