美文网首页码农的世界收藏ios
iOS秀场类直播间实时弹幕

iOS秀场类直播间实时弹幕

作者: nzkaw | 来源:发表于2019-01-20 18:21 被阅读5次

    最近项目中直播间里添加了实时弹幕需求,本篇记录一下实现过程。


    先看一下最终做出来的效果

    效果图.gif
    基本的实现逻辑,客户端在接收到一条弹幕消息之后,根据消息生成对应的弹幕样式,添加到屏幕上,然后做简单的平移动画,当移动超出屏幕范围之后自动移除,防止内存持续增长。有了一个简单的思路,下面就开始动手用代码来实现。

    首先定义一个弹幕容器,实现接收弹幕消息方法,使容器可以处理服务返回的弹幕消息

    @interface DSHBarrageView : UIView
    
    @property (strong ,nonatomic) CADisplayLink *timer; // 用来实现弹幕的平移动画
    - (void)destroy; // 销毁定时器
    - (void)receivedMessage:(id)message; // 收到一条弹幕消息
    @end
    

    实现

    @implementation DSHBarrageView
    
    // 收到一条弹幕消息
    - (void)receivedMessage:(id)message; {
        UILabel *cell = [[UILabel alloc] init];
        cell.font = [UIFont systemFontOfSize:14];
        cell.textColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor blackColor];
        cell.textAlignment = NSTextAlignmentCenter;
        cell.text = [NSString stringWithFormat:@"弹幕消息:%@" ,message];
        [self addSubview:cell];
        
        [cell sizeToFit];
        CGRect frame = cell.frame;
        frame.origin.x = self.frame.size.width;
        frame.origin.y = 44.f;
        frame.size.width = 100.f;
        cell.frame = frame;
        
        if (!_timer) { // 当接收到弹幕消息后开启定时器
            _timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
            [_timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        }
    }
    - (void)update {
        NSInteger cellCount = 0;
        for (UILabel *cell in self.subviews) {
            if ([cell isKindOfClass:[UILabel class]]) {
                CGRect frame = cell.frame;
                frame.origin.x -= 1.f;
                cell.frame = frame;
                if (CGRectGetMaxX(frame) <= 0) {
                    [cell removeFromSuperview]; // 当超出屏幕时自动移除
                } else {
                    cellCount ++;
                }
            }
        }
        if (cellCount <= 0) {
            [self destroy]; // 检测到没有弹幕时自动销毁定时器
        }
    }
    - (void)destroy; {
        [_timer invalidate];
        _timer = nil;
    }
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        UIView *view = [super hitTest:point withEvent:event];
        if (view == self) {
            return nil;
        }
        return view;
    }
    @end
    

    这里已经简单的实现了一条弹幕从创建到移动再到销毁的整个过程,在ViewController.m实现以下代码,运行看一下效果。

    #import "ViewController.h"
    #import "DSHBarrageView.h"
    
    @interface ViewController ()
    @property (strong ,nonatomic) DSHBarrageView *barrageView;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        _barrageView = [[DSHBarrageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [self.view addSubview:_barrageView];
    }
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        static NSInteger index = 0;
        index ++;
        [_barrageView receivedMessage:@(index)];
    }
    @end
    
    效果图.gif

    嗯虽然很粗糙,但是弹幕已经可以出来了,不过有个问题就是弹幕重叠了,这里可以加个数组来临时保存接收到的弹幕消息,等检测到有空位置了再处理。

    @interface DSHBarrageView : UIView
    @property (strong ,nonatomic) NSMutableArray *barrageMessages; // 管理队列中的弹幕消息
    @end
    

    对应的修改.m文件实现检测逻辑

    // 收到一条弹幕消息
    - (void)receivedMessage:(id)message; {
        BOOL idle = [self idle];
        if (!idle) {
            if (!_barrageMessages) {
                _barrageMessages = [NSMutableArray array];
            }
            [_barrageMessages addObject:message];
        } else {
            [self showBarrageCellWithBarrageMessage:message];
        }
    }
    // 检测是否有空位置可供弹幕展示
    - (BOOL)idle {
        BOOL idle = YES;
        for (UILabel *label in self.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (CGRectGetMaxX(label.frame) >= self.frame.size.width) {
                    idle = NO; break;
                }
            }
        }
        return idle;
    }
    - (void)showBarrageCellWithBarrageMessage:(id)message {
        UILabel *cell = [[UILabel alloc] init];
        cell.font = [UIFont systemFontOfSize:14];
        cell.textColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor blackColor];
        cell.textAlignment = NSTextAlignmentCenter;
        cell.text = [NSString stringWithFormat:@"弹幕消息:%@" ,message];
        [self addSubview:cell];
        
        [cell sizeToFit];
        CGRect frame = cell.frame;
        frame.origin.x = self.frame.size.width;
        frame.origin.y = 44.f;
        frame.size.width = 100.f;
        cell.frame = frame;
        
        if (!_timer) { // 当接收到弹幕消息后开启定时器
            _timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
            [_timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        }
    }
    - (void)update {
        NSInteger cellCount = 0;
        for (UILabel *cell in self.subviews) {
            if ([cell isKindOfClass:[UILabel class]]) {
                CGRect frame = cell.frame;
                frame.origin.x -= 1.f;
                cell.frame = frame;
                if (CGRectGetMaxX(frame) <= 0) {
                    [cell removeFromSuperview]; // 当超出屏幕时自动移除
                } else {
                    cellCount ++;
                }
            }
        }
        id message = _barrageMessages.firstObject;
        if (message && [self idle]) { // 检测到位置已经空出来了,处理队列中的消息
            [_barrageMessages removeObject:message];
            [self showBarrageCellWithBarrageMessage:message];
            cellCount ++;
        }
        if (cellCount <= 0) {
            [self destroy]; // 检测到没有弹幕时自动销毁定时器
        }
    }
    

    好的再次运行

    效果图.gif
    到这里弹幕的核心逻辑就完成了,接下来需要支持多条弹幕通道,自定义弹幕样式,自定义弹幕滚动速度,完整的代码可以点击这里查看,整个Demo代码不算少,这里就不贴全部了。

    相关文章

      网友评论

        本文标题:iOS秀场类直播间实时弹幕

        本文链接:https://www.haomeiwen.com/subject/fsmxjqtx.html