纯血鸿蒙APP实战开发——图片缩放效果实现
2025-03-08 本文已影响0人
迪士尼在逃程序员
介绍
图片预览在应用开发中是一种常见场景,在诸如QQ、微信、微博等应用中均被广泛使用。本模块基于Image组件实现了简单的图片预览功能。
使用说明:
- 双指捏合对图片进行缩放
- 双击图片进行图片的大小切换,在放大状态下,双击可恢复默认状态
- 图片在放大模式下,滑动图片查看图片的对应位置
效果图预览
实现思路
- 使用matrix实现图片的缩放。
@State matrix: matrix4.Matrix4Transit = matrix4.identity().copy();
Image(this.imagePixelMap)
.transform(this.matrix)
- 使用offset属性对图片进行偏移。
@State imageOffsetInfo: OffsetModel = new OffsetModel(0, 0);
Image(this.imagePixelMap)
.offset({
x: this.imageOffsetInfo.currentX,
y: this.imageOffsetInfo.currentY
})
- Image的objectFit属性设置为Cover,锁定图片宽高比,并使其能够超出父组件边界显示。
Image(this.imagePixelMap)
.objectFit(ImageFit.Cover)
- 提前计算图片信息,并通过Image的宽或高配合aspectRatio设置默认尺寸。
initCurrentImageInfo(): void {
this.matrix = matrix4.identity().copy();
const imageSource: image.ImageSource = image.createImageSource(this.imageUri);
imageSource.getImageInfo(0).then((data: image.ImageInfo) => {
this.imageWHRatio = data.size.width / data.size.height;
this.imageDefaultSize = this.calcImageDefaultSize(this.imageWHRatio, windowSizeManager.get());
if (this.imageDefaultSize.width === windowSizeManager.get().width) {
this.fitWH = "width";
} else {
this.fitWH = "height";
}
this.imageScaleInfo.maxScaleValue += this.fitWH === "width" ?
(windowSizeManager.get().height / this.imageDefaultSize.height) :
(windowSizeManager.get().width / this.imageDefaultSize.width);
}).catch((err: BusinessError) => {
console.error(`[error][getImageInfo]${err.message}`);
});
imageSource.createPixelMap().then((data: image.PixelMap) => {
this.imagePixelMap = data;
}).catch((err: BusinessError) => {
console.error(`[error][createPixelMap]${err.message}`);
});
}
Image(this.imagePixelMap)
.width(this.fitWH === "width" ? $r("app.string.image_default_width") : undefined)
.height(this.fitWH === "height" ? $r("app.string.image_default_height") : undefined)
.aspectRatio(this.imageWHRatio)
高性能知识点
模块依赖
工程结构&模块类型
imageviewer // har类型
|---constants // 常量
|---model // 模型层-自定义数据模型
|---utils // 工具类
|---view // 视图层-图片预览方案涉及的主要组件
|---|---ImageViewerView.ets // 视图层-入口
|---|---ImageItemView.ets // 视图层-单张图片的显示组件
其他
- TODO:增强需求:限制位移边界
- TODO:增强需求:多图切换
写在最后
- 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
- 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
- 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
- 想要获取更多完整鸿蒙最新学习知识点,请移步前往小编:
https://gitee.com/MNxiaona/733GH/blob/master/jianshu