鸿蒙开发实现弹幕功能如下:
弹幕轮播组件:BannerScroll
import type { IDanMuInfoList, IDanMuInfoItem } from '../model/DanMuData'
//定义组件
@Component
export default struct BannerScroll {//@Watch 用来监视状态数据的变化,包括:@State、@Prop、@Link、@Provide、@Consume//一旦状态数据变化,监视的回调就会调用// 我们可以在监视的回调中执行应用需要的特定逻辑@Link @Watch('start') bannerList: IDanMuInfoList@State scrollList: IDanMuInfoList = []scroller: Scroller = new Scroller()aboutToAppear() {this.start()}aboutToDisappear() {this.stop()}xOffset: number = 0 // 位移距离timeId: number // 定时器标识duration: number = Math.round(1000 / 60) // 位移间隔时间move() {this.stop()this.timeId = setTimeout(() => {this.xOffset += 4// 动画的持续时间,不能大于或等于定时器的间隔this.scroller.scrollTo({xOffset: this.xOffset / 10,yOffset: 0,animation: { duration: this.duration - 5, curve: Curve.Linear }})this.move()}, this.duration)}start() {const bannerList = this.bannerList;if (bannerList.length === 0) {return;}this.scrollList = [...bannerList, ...bannerList].map((item, index) => {return {...item,id: index}})this.move()}stop() {clearInterval(this.timeId);}reset(firstIndex: number) {if (firstIndex === this.bannerList.length) {this.xOffset = 0;this.scroller.scrollTo({ xOffset: 0, yOffset: 0, animation: { duration: 0, curve: Curve.Linear } })}}build() {List({ scroller: this.scroller }) {ForEach(this.scrollList, (banner: IDanMuInfoItem) => {ListItem() {Row({ space: 6 }) {Text(banner.content).fontSize(14)}.padding({ top: 6, left: 6, bottom: 6, right: 10 }).borderRadius(42).backgroundColor('#CDFFD9').margin({ left: 10 })}}, banner => banner.id)}.listDirection(Axis.Horizontal) // 排列方向.edgeEffect(EdgeEffect.None) // 滑动到边缘无效果.onScrollIndex(this.reset.bind(this)).width('100%').cachedCount(4).hitTestBehavior(HitTestMode.None)}
}
关注‘猿来编码’,回复弹幕,获取更多,以后也会继续分享鸿蒙相关知识,相互学习。谢谢