温馨提示:本篇博客的详细代码已发布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下载运行哦!
@Component
export struct ImageViewerViewComponent {
// 状态管理
@State isEnableSwipe: boolean = true;
@Provide bgc: Color = Color.White;
// 数据源
imageDataSource = new CommonLazyDataSourceModel<string>();
// 上下文与控制器
context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
swipeController: SwiperController = new SwiperController();
// 生命周期
aboutToAppear() { /* 初始化数据 */ }
build() { /* 构建UI */ }
}
@State isEnableSwipe
:控制Swiper是否允许滑动@Link
双向绑定@Provide bgc
:全局背景色@Consume
在子组件中同步更新 aboutToAppear() {
const resourceDir = this.context.resourceDir;
this.imageDataSource.pushData(resourceDir + '/image.jpg');
}
context.resourceDir
获取应用资源目录/resources/base/media/image.jpg
CommonLazyDataSourceModel
应实现数据分页/增量加载 Swiper(this.swipeController)
.disableSwipe(!this.isEnableSwipe)
.cachedCount(3)
.loop(false)
LazyForEach(this.imageDataSource, (item, index) => {
ImageItemView({ imageUri: item })
.size(100%, 100%)
})
.disableSwipe(!this.isEnableSwipe)
isEnableSwipe = false
isEnableSwipe = true
.expandSafeArea([SafeAreaType.SYSTEM],
[SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
.onClick(() => {
this.bgc = this.bgc === White ? Black : White;
})
.width($r("app.string.imageviewer_full_size"))
{
"name": "imageviewer_full_size",
"value": "100%"
}
graph TD
A[ImageViewerView] -->|控制| B(Swiper)
A -->|提供| C[bgc状态]
B -->|使用| D[LazyForEach]
D -->|创建| E[ImageItemView]
E -->|消费| C
imageUri
@Link
更新isEnableSwipe
@Provide/@Consume
共享bgc
.onChange((index) => {
// 预加载前后3张图片
this.imageDataSource.preload(index-3, index+3);
})
// 在aboutToAppear中添加
profiler.trace(this.context, "ImageViewerRender");
.onSwipe((event) => {
if (event.direction === SwiperDirection.Left) {
analytics.send("swipe_left");
}
})
Q1:图片加载闪烁
class ImageCache {
static cache = new LRUCache(50);
static get(uri) { /* ... */ }
static set(uri, data) { /* ... */ }
}
Q2:快速滑动卡顿
Q3:内存占用过高
aboutToDisappear() {
this.imageDataSource.clearCache();
}
该组件作为图片查看器的核心容器,通过:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。