HarmonyOS开发:显示图片功能详解
目录
前言
Image组件基础
1、Image组件概述
2、加载图片资源
3、存档图类型数据源
(1)本地资源
(2)网络资源
(3)Resource资源
(4)媒体库file://data/storage
(5)base64
4、多媒体像素图
(1)创建PixelMap状态变量。
(2)引用多媒体。
5、可绘制描述符
(1)引入模块
(2)创建DrawableDescriptor对象
(3)封装辅助方法
(4)显示图片
显示矢量图
添加属性
(1)设置图片缩放类型
(2)图片插值
(3)设置图片渲染模式
(4)设置图片解码尺寸
(5)为图片添加滤镜效果
(6)同步加载图片
事件调用
Image组件的应用
1、图片资源优化
2、错误处理与容错机制
3、性能监控与分析
结束语
前言
在现在用户对应用要求很高的时代,用户界面的视觉效果对于提升用户体验起着至关重要的作用,而图片作为视觉元素的核心组成部分,在各类应用中扮演着不可或缺的角色。无论是用于展示产品的精美图片、传递信息的图标,还是营造氛围的背景图,恰当且高效的图片使用都能极大地增强应用的吸引力和易用性。HarmonyOS作为面向未来全场景智能设备的操作系统,为开发者提供了强大的图像处理和展示能力,其中Image组件便是实现丰富视觉效果的关键工具之一。对于HarmonyOS开发者而言,深入理解并掌握Image组件的使用方法,不仅可以帮助我们构建出更具吸引力的用户界面,还能在性能优化和资源管理方面发挥重要作用,通过合理配置Image组件的属性和方法,我们能够实现图片的高效加载、流畅展示以及与其他UI组件的无缝集成。那么本文就来深入探讨HarmonyOS中Image组件的使用方法,从基础属性配置到高级功能实现,从静态图片展示到动态效果处理,全方位剖析Image组件的特性和应用场景,通过丰富的示例代码和详细的解释说明,帮助大家快速掌握Image组件的使用要点。
Image组件基础
开发者经常需要在应用中显示一些图片,比如:按钮中的icon、网络图片、本地图片等。在应用中显示图片需要使用Image组件实现,Image为图片组件,常用于在应用中显示图片,Image支持加载PixelMap、ResourceStr和DrawableDescriptor类型的数据源,支持png、jpg、jpeg、bmp、svg、webp、gif和heif类型的图片格式,不支持apng和svga格式。
1、Image组件概述
在HarmonyOS的UI开发中,Image组件是用于展示图片资源的基本组件,上面也介绍了它支持多种图片格式,如PNG、JPEG等,并且提供了丰富的属性和方法来控制图片的显示效果、加载方式以及与其他UI元素的交互。通过合理使用Image组件,开发者可以轻松地在应用中添加各种图片资源,提升应用的视觉表现力。Image通过调用接口来创建,接口调用形式如下:
Image(src: PixelMap | ResourceStr | DrawableDescriptor)
这个接口通过图片数据源获取图片,支持本地图片和网络图片的渲染展示。其中,src是图片的数据源,加载方式请参考加载图片资源。
2、加载图片资源
Image支持加载存档图、多媒体像素图和可绘制描述符三种类型。
3、存档图类型数据源
存档图类型的数据源可以分为本地资源、网络资源、Resource资源、媒体库资源和base64。
(1)本地资源
创建文件夹,将本地图片放入ets文件夹下的任意位置。Image组件引入本地图片路径,即可显示图片(根目录为ets文件夹)。
Image('images/view.jpg').width(200)
加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。
(2)网络资源
引入网络图片需申请权限ohos.permission.INTERNET,具体申请方式请参考声明权限,此时,Image组件的src参数为网络图片的链接。当前Image组件仅支持加载简单网络图片。Image组件首次加载网络图片时,需要请求网络资源,非首次加载时,默认从缓存中直接读取图片,更多图片缓存设置请参考setImageCacheCount、setImageRawDataCacheSize、setImageFileCacheSize。但是,这三个图片缓存接口并不灵活,且后续不继续演进,对于复杂情况,更推荐使用ImageKnife。
这里需要说明的是网络图片必须支持RFC 9113标准,否则会导致加载失败。如果下载的网络图片大于10MB或一次下载的网络图片数量较多,建议使用HTTP工具提前预下载,提高图片加载性能,方便应用侧管理数据。
在显示网络图片时,Image 组件会将下载与缓存功能剥离至缓存下载模块进行统一管理。缓存下载模块提供独立的预下载接口,允许应用开发者在创建Image组件前预下载所需图片。组件创建后,通过向缓存下载模块请求数据,从而优化了Image组件的显示流程。网络缓存的位置位于应用根目录下的cache目录中。
Image('https://www.sanzhanggui.com/example.JPG') // 实际使用时请替换为真实地址
(3)Resource资源
使用资源格式可以跨包/跨模块引入图片,resources文件夹下的图片都可以通过$r资源接口读取到并转换到Resource格式。resources文件目录如下图所示:
具体的调用方式如下所示:
Image($r('app.media.example'))
另外,还可以将图片放在rawfile文件夹下,如下所示:
具体的调用方式如下所示:
Image($rawfile('example1.png'))
(4)媒体库file://data/storage
支持file://路径前缀的字符串,用于访问通过选择器提供的图片路径。
a.调用接口获取图库的照片url如下所示:
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State imgDatas: string[] = [];
// 获取照片url集
getAllImg() {
try {
let PhotoSelectOptions:photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker:photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult:photoAccessHelper.PhotoSelectResult) => {
this.imgDatas = PhotoSelectResult.photoUris;
}).catch((err:Error) => {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
});
} catch (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
}
}
// aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
async aboutToAppear() {
this.getAllImg();
}
// 使用imgDatas的url加载图片。
build() {
Column() {
Grid() {
ForEach(this.imgDatas, (item:string) => {
GridItem() {
Image(item)
.width(200)
}
}, (item:string):string => JSON.stringify(item))
}
}.width('100%').height('100%')
}
}
b.从媒体库获取的url格式通常如下所示:
Image('file://media/Photos/5').width(200)
(5)base64
路径格式为data:image/[png|jpeg|bmp|webp|heif];base64,[base64 data],其中[base64 data]为Base64字符串数据。Base64格式字符串可用于存储图片的像素数据,在网页上使用较为广泛。
4、多媒体像素图
PixelMap是图片解码后的像素图,以下示例将加载的网络图片返回的数据解码成PixelMap格式,再显示在Image组件上。
(1)创建PixelMap状态变量。
@State image: PixelMap | undefined = undefined;
(2)引用多媒体。
- 引用网络权限与媒体库权限,如下所示:
import { http } from '@kit.NetworkKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
- 填写网络图片地址,如下所示:
let OutData: http.HttpResponse
http.createHttp().request("https://www.sanzhanggui.com/xxx.png",
(error: BusinessError, data: http.HttpResponse) => {
if (error) {
} else {
OutData = data
}
}
)
- 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
let code: http.ResponseCode | number = OutData.responseCode;
if (http.ResponseCode.OK === code) {
let imageData: ArrayBuffer = OutData.result as ArrayBuffer;
let imageSource: image.ImageSource = image.createImageSource(imageData);
class tmp {
height: number = 100;
width: number = 100;
}
let si: tmp = new tmp()
let options: Record = {
'alphaType': 0, // 透明度
'editable': false, // 是否可编辑
'pixelFormat': 3, // 像素格式
'scaleMode': 1, // 缩略值
'size': { height: 100, width: 100 }
} // 创建图片大小
class imagetmp {
image: PixelMap | undefined = undefined;
set(val: PixelMap) {
this.image = val;
}
}
imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
let im = new imagetmp();
im.set(pixelMap);
})
}
- 显示图片,如下所示:
class htp{
httpRequest: Function | undefined = undefined;
set(){
if(this.httpRequest){
this.httpRequest();
}
}
}
Button("获取网络图片")
.onClick(() => {
let sethtp = new htp();
sethtp.set();
})
Image(this.image).height(100).width(100)
同时,也可以传入pixelMap创建PixelMapDrawableDescriptor对象,用来显示图片,具体如下所示:
import { DrawableDescriptor, PixelMapDrawableDescriptor } from '@kit.ArkUI';
class htp{
httpRequest: Function | undefined = undefined;
set(){
if(this.httpRequest){
this.httpRequest();
}
}
}
Button("获取网络图片")
.onClick(() => {
let sethtp = new htp();
sethtp.set();
this.drawablePixelMap = new PixelMapDrawableDescriptor(this.image);
})
Image(this.drawablePixelMap).height(100).width(100)
5、可绘制描述符
另外,DrawableDescriptor是ArkUI提供的一种高级图片抽象机制,它通过将图片资源封装为可编程对象,实现了传统Image组件难以实现的动态组合与运行时控制功能。开发者可利用它实现图片的分层叠加(如徽章图标)、动态属性调整(如颜色滤镜)、复杂动画序列等高级效果,适用于需要灵活控制图片展现或实现复杂视觉交互的场景。具体的使用详细步骤如下所示。
(1)引入模块
import { DrawableDescriptor, PixelMapDrawableDescriptor, LayeredDrawableDescriptor, AnimatedDrawableDescriptor, AnimationOptions } from '@kit.ArkUI';
(2)创建DrawableDescriptor对象
// 声明DrawableDescriptor对象
@State pixmapDesc: DrawableDescriptor | null = null;
@State pixelMapDesc: PixelMapDrawableDescriptor | null = null;
@State layeredDesc: LayeredDrawableDescriptor | null = null;
@State animatedDesc: AnimatedDrawableDescriptor | null = null;
// 动画配置
private animationOptions: AnimationOptions = {
duration: 1000, // 总时长1秒
iterations: -1 // 无限循环
};
async aboutToAppear() {
const resManager = getContext().resourceManager;
// 创建普通DrawableDescriptor
this.pixmapDesc = (await resManager.getDrawableDescriptor($r('app.media.app_icon').id)) as DrawableDescriptor;
// 创建PixelMapDrawableDescriptor
const pixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'));
this.pixelMapDesc = new PixelMapDrawableDescriptor(pixelMap);
// 创建分层图标
const foreground = await this.getDrawableDescriptor($r('app.media.foreground'));
const background = await this.getDrawableDescriptor($r('app.media.background'));
this.layeredDesc = new LayeredDrawableDescriptor(foreground, background);
// 创建动画图片(需加载多张图片)
const frame1 = await this.getPixmapFromMedia($r('app.media.startIcon'));
const frame2 = await this.getPixmapFromMedia($r('app.media.app_icon'));
const frame3 = await this.getPixmapFromMedia($r('app.media.background'));
this.animatedDesc = new AnimatedDrawableDescriptor([frame1, frame2, frame3], this.animationOptions);
}
(3)封装辅助方法
下面是为简化DrawableDescriptor创建过程而封装的辅助方法,如下所示:
// 辅助方法:从资源获取PixelMap
private async getPixmapFromMedia(resource: Resource): Promise {
const unit8Array = await getContext().resourceManager.getMediaContent({
bundleName: resource.bundleName,
moduleName: resource.moduleName,
id: resource.id
});
const imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength));
const pixelMap = await imageSource.createPixelMap({
desiredPixelFormat: image.PixelMapFormat.RGBA_8888
});
await imageSource.release();
return pixelMap;
}
// 辅助方法:获取DrawableDescriptor
private async getDrawableDescriptor(resource: Resource): Promise {
const resManager = getContext().resourceManager;
return (await resManager.getDrawableDescriptor(resource.id)) as DrawableDescriptor;
}
(4)显示图片
// 显示普通图片
Image(this.pixmapDesc)
.width(100)
.height(100)
.border({ width: 1, color: Color.Black })
// 显示PixelMap图片
Image(this.pixelMapDesc)
.width(100)
.height(100)
.border({ width: 1, color: Color.Red })
// 显示分层图标
if (this.layeredDesc) {
Image(this.layeredDesc)
.width(100)
.height(100)
.border({ width: 1, color: Color.Blue })
}
// 显示动画图片
if (this.animatedDesc) {
Image(this.animatedDesc)
.width(200)
.height(200)
.margin({ top: 20 })
}
显示矢量图
Image组件可显示矢量图(svg格式的图片),如果SVG图片没有原始大小,需要给Image组件设置宽高,否则不显示。SVG图片不支持通过image标签引用svg格式和gif格式的本地其他图片。svg格式的图片可以使用fillColor属性改变图片的绘制颜色,具体如下所示:
Image($r('app.media.cloud')) .width(50) .fillColor(Color.Blue)
关于矢量图引用位图,如果Image加载的Svg图源中包含对本地位图的引用,则Svg图源的路径应当设置为以ets为根目录的工程路径,同时,本地位图的路径应设置为与Svg图源同级的相对路径。Image加载的Svg图源路径设置方法如下所示:
Image("images/icon.svg") .width(50) .height(50)
项目中文件工程路径示例如下图所示:
添加属性
给Image组件设置属性可以使图片显示更灵活,达到一些自定义的效果,下面介绍几个常用属性的使用示例。
(1)设置图片缩放类型
通过objectFit属性使图片缩放到高度和宽度确定的框内。
@Entry
@Component
struct MyComponent {
scroller: Scroller = new Scroller();
build() {
Scroll(this.scroller) {
Column() {
Row() {
Image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
.objectFit(ImageFit.Contain)
.margin(15)
.overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
Image($r('app.media.ic_img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
.objectFit(ImageFit.Cover)
.margin(15)
.overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
Image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 自适应显示。
.objectFit(ImageFit.Auto)
.margin(15)
.overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Row() {
Image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 不保持宽高比进行放大缩小,使得图片充满显示边界。
.objectFit(ImageFit.Fill)
.margin(15)
.overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
Image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持宽高比显示,图片缩小或者保持不变。
.objectFit(ImageFit.ScaleDown)
.margin(15)
.overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
Image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持原有尺寸显示。
.objectFit(ImageFit.None)
.margin(15)
.overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
}
}
}
}
(2)图片插值
当原图分辨率较低并且放大显示时,图片会模糊出现锯齿,这时候可以使用interpolation属性对图片进行插值,使图片显示得更清晰,具体如下所示:
@Entry
@Component
struct Index {
build() {
Column() {
Row() {
Image($r('app.media.grass'))
.width('40%')
.interpolation(ImageInterpolation.None)
.borderWidth(1)
.overlay("Interpolation.None", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
.margin(10)
Image($r('app.media.grass'))
.width('40%')
.interpolation(ImageInterpolation.Low)
.borderWidth(1)
.overlay("Interpolation.Low", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
.margin(10)
}.width('100%')
.justifyContent(FlexAlign.Center)
Row() {
Image($r('app.media.grass'))
.width('40%')
.interpolation(ImageInterpolation.Medium)
.borderWidth(1)
.overlay("Interpolation.Medium", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
.margin(10)
Image($r('app.media.grass'))
.width('40%')
.interpolation(ImageInterpolation.High)
.borderWidth(1)
.overlay("Interpolation.High", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
.margin(10)
}.width('100%')
.justifyContent(FlexAlign.Center)
}
.height('100%')
}
}
(3)设置图片渲染模式
通过renderMode属性设置图片的渲染模式为原色或黑白,具体如下所示:
@Entry
@Component
struct MyComponent {
build() {
Column({ space: 10 }) {
Row({ space: 50 }) {
Image($r('app.media.example'))
// 设置图片的渲染模式为原色
.renderMode(ImageRenderMode.Original)
.width(100)
.height(100)
.border({ width: 1 })
// overlay是通用属性,用于在组件上显示说明文字
.overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
Image($r('app.media.example'))
// 设置图片的渲染模式为黑白
.renderMode(ImageRenderMode.Template)
.width(100)
.height(100)
.border({ width: 1 })
.overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
}.height(150).width('100%').padding({ top: 20,right: 10 })
}
}
(4)设置图片解码尺寸
通过sourceSize属性设置图片解码尺寸,降低图片的分辨率。原图尺寸为1280*960,该示例将图片解码为40*40和90*90,具体如下所示:
@Entry
@Component
struct Index {
build() {
Column() {
Row({ space: 50 }) {
Image($r('app.media.example'))
.sourceSize({
width: 40,
height: 40
})
.objectFit(ImageFit.ScaleDown)
.aspectRatio(1)
.width('25%')
.border({ width: 1 })
.overlay('width:40 height:40', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
Image($r('app.media.example'))
.sourceSize({
width: 90,
height: 90
})
.objectFit(ImageFit.ScaleDown)
.width('25%')
.aspectRatio(1)
.border({ width: 1 })
.overlay('width:90 height:90', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
}.height(150).width('100%').padding(20)
}
}
}
(5)为图片添加滤镜效果
通过colorFilter修改图片的像素颜色,为图片添加滤镜,具体如下所示:
@Entry
@Component
struct Index {
build() {
Column() {
Row() {
Image($r('app.media.example'))
.width('40%')
.margin(10)
Image($r('app.media.example'))
.width('40%')
.colorFilter(
[1, 1, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0])
.margin(10)
}.width('100%')
.justifyContent(FlexAlign.Center)
}
}
}
(6)同步加载图片
一般情况下,图片加载流程会异步进行,以避免阻塞主线程,影响UI交互。但是特定情况下,图片刷新时会出现闪烁,这时可以使用syncLoad属性,使图片同步加载,从而避免出现闪烁。不建议图片加载较长时间时使用,会导致页面无法响应,具体如下所示:
Image($r('app.media.icon'))
.syncLoad(true)
事件调用
通过在Image组件上绑定onComplete事件,图片加载成功后可以获取图片的必要信息。如果图片加载失败,也可以通过绑定onError回调来获得结果。具体操作如下所示:
@Entry
@Component
struct MyComponent {
@State widthValue: number = 0;
@State heightValue: number = 0;
@State componentWidth: number = 0;
@State componentHeight: number = 0;
build() {
Column() {
Row() {
Image($r('app.media.ic_img_2'))
.width(200)
.height(150)
.margin(15)
.onComplete(msg => {
if(msg){
this.widthValue = msg.width;
this.heightValue = msg.height;
this.componentWidth = msg.componentWidth;
this.componentHeight = msg.componentHeight;
}
})
// 图片获取失败,打印结果
.onError(() => {
console.info('load image fail')
})
.overlay('
width: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '
componentWidth: ' + String(this.componentWidth) + '
componentHeight: ' + String(this.componentHeight), {
align: Alignment.Bottom,
offset: { x: 0, y: 60 }
})
}
}
}
}
Image组件的应用
1、图片资源优化
为了提升应用的性能,我们需要对图片资源进行优化。包括压缩图片大小、选择合适的图片格式、使用图片懒加载等。通过这些优化措施,可以减少图片加载时间,降低内存占用,提升应用的响应速度。
2、错误处理与容错机制
在图片加载过程中,可能会出现各种错误,如网络问题、图片资源不存在等。我们需要为Image组件添加错误处理机制,确保在图片加载失败时,能够提供友好的提示或备用图片。
3、性能监控与分析
在应用开发过程中,我们需要对图片加载性能进行监控和分析。通过监控图片加载时间、内存占用等指标,可以及时发现性能瓶颈,优化应用性能。
结束语
通过本文的详细介绍,详细介绍了HarmonyOS开发中Image组件的使用方法,从基础属性配置到高级功能实现,从静态图片展示到动态效果处理,全方位剖析了Image组件的特性和应用场景,Image组件作为HarmonyOS UI开发中的重要组成部分,为开发者提供了强大的图片处理和展示能力,可以帮助大家构建出更具吸引力的用户界面。在实际开发中,合理使用Image组件不仅可以提升应用的视觉表现力,还能在性能优化和资源管理方面发挥重要作用,通过动态加载、懒加载、动画效果、适配与响应式设计等技术手段,我们可以实现图片的高效加载、流畅展示以及与其他UI组件的无缝集成。同时,结合图片资源优化、错误处理与容错机制、性能监控与分析等最佳实践,我们能够进一步提升应用的质量和用户体验。希望本文的介绍和示例代码能够帮助你在HarmonyOS开发中更好地使用Image组件。