iOS秀場類直播間實(shí)時(shí)彈幕

最近項(xiàng)目中直播間里添加了實(shí)時(shí)彈幕需求,本篇記錄一下實(shí)現(xiàn)過程。


先看一下最終做出來的效果

效果圖.gif

基本的實(shí)現(xiàn)邏輯,客戶端在接收到一條彈幕消息之后,根據(jù)消息生成對應(yīng)的彈幕樣式,添加到屏幕上,然后做簡單的平移動(dòng)畫,當(dāng)移動(dòng)超出屏幕范圍之后自動(dòng)移除,防止內(nèi)存持續(xù)增長。有了一個(gè)簡單的思路,下面就開始動(dòng)手用代碼來實(shí)現(xiàn)。


首先定義一個(gè)彈幕容器,實(shí)現(xiàn)接收彈幕消息方法,使容器可以處理服務(wù)返回的彈幕消息

@interface DSHBarrageView : UIView

@property (strong ,nonatomic) CADisplayLink *timer; // 用來實(shí)現(xiàn)彈幕的平移動(dòng)畫
- (void)destroy; // 銷毀定時(shí)器
- (void)receivedMessage:(id)message; // 收到一條彈幕消息
@end

實(shí)現(xiàn)

@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) { // 當(dāng)接收到彈幕消息后開啟定時(shí)器
        _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]; // 當(dāng)超出屏幕時(shí)自動(dòng)移除
            } else {
                cellCount ++;
            }
        }
    }
    if (cellCount <= 0) {
        [self destroy]; // 檢測到?jīng)]有彈幕時(shí)自動(dòng)銷毀定時(shí)器
    }
}
- (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

這里已經(jīng)簡單的實(shí)現(xiàn)了一條彈幕從創(chuàng)建到移動(dòng)再到銷毀的整個(gè)過程,在ViewController.m實(shí)現(xiàn)以下代碼,運(yùn)行看一下效果。

#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

嗯雖然很粗糙,但是彈幕已經(jīng)可以出來了,不過有個(gè)問題就是彈幕重疊了,這里可以加個(gè)數(shù)組來臨時(shí)保存接收到的彈幕消息,等檢測到有空位置了再處理。

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

對應(yīng)的修改.m文件實(shí)現(xiàn)檢測邏輯

// 收到一條彈幕消息
- (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) { // 當(dāng)接收到彈幕消息后開啟定時(shí)器
        _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]; // 當(dāng)超出屏幕時(shí)自動(dòng)移除
            } else {
                cellCount ++;
            }
        }
    }
    id message = _barrageMessages.firstObject;
    if (message && [self idle]) { // 檢測到位置已經(jīng)空出來了,處理隊(duì)列中的消息
        [_barrageMessages removeObject:message];
        [self showBarrageCellWithBarrageMessage:message];
        cellCount ++;
    }
    if (cellCount <= 0) {
        [self destroy]; // 檢測到?jīng)]有彈幕時(shí)自動(dòng)銷毀定時(shí)器
    }
}

好的再次運(yùn)行

效果圖.gif

到這里彈幕的核心邏輯就完成了,接下來需要支持多條彈幕通道,自定義彈幕樣式,自定義彈幕滾動(dòng)速度,完整的代碼可以點(diǎn)擊這里查看,整個(gè)Demo代碼不算少,這里就不貼全部了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,621評論 1 32
  • 昨天是什么日子? 周二 終極目標(biāo): 事業(yè)有成、個(gè)人成長、家庭幸福、人際良好、財(cái)政自由 最重要的三件事: 1.學(xué)習(xí)得...
    香脆酥酥閱讀 314評論 0 1
  • 1、每日營養(yǎng)分享 營養(yǎng)不僅僅是書面的語言,更是生活的細(xì)節(jié)! 2、感謝今天看到的文章,在禮儀方面需要做到的幾點(diǎn)事項(xiàng),...
    芝華的幸福世界閱讀 154評論 0 0
  • 很久了 我們不說話 已經(jīng)很久了 不說那就不說吧 我知道這樣的開始 就已經(jīng)意味著什么了 等到某月某號 你我變成陌生人...
    夢琪琪昂閱讀 575評論 0 1
  • 《尷尬的詩人》 /黎峰 我是尷尬的詩人,行吟離騷 那冬日陽光放出的金線,遙遠(yuǎn)的微溫 我是防風(fēng)玻璃堅(jiān)守的透明,矛盾的...
    黎峰小峰峰閱讀 3,205評論 76 104

友情鏈接更多精彩內(nèi)容