• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 显示图片 (Image)
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @liyujie43-->
5<!--Designer: @weixin_52725220-->
6<!--Tester: @xiong0104-->
7<!--Adviser: @HelloCrease-->
8
9开发者经常需要在应用中显示一些图片,例如:按钮中的icon、网络图片、本地图片等。在应用中显示图片需要使用Image组件实现,Image支持多种图片格式,包括png、jpg、bmp、svg、gif和heif,不支持apng和svga格式,具体用法请参考[Image](../reference/apis-arkui/arkui-ts/ts-basic-components-image.md)组件。
10
11
12Image通过调用接口来创建,接口调用形式如下:
13
14```ts
15Image(src: PixelMap | ResourceStr | DrawableDescriptor)
16```
17
18
19该接口通过图片数据源获取图片,支持本地图片和网络图片的渲染展示。其中,src是图片的数据源,加载方式请参考[加载图片资源](#加载图片资源)。
20
21如果图片加载过程中出现白色块,请参考[Image白块问题解决方案](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-image-white-lump-solution)。如果图片加载时间过长,请参考[预置图片资源加载优化](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-texture-compression-improve-performance)22
23
24## 加载图片资源
25
26Image支持加载存档图、多媒体像素图和可绘制描述符三种类型。
27
28
29### 存档图类型数据源
30
31存档图类型的数据源可以分为本地资源、网络资源、Resource资源、媒体库资源和base64。
32
33- 本地资源
34
35  创建文件夹,将本地图片放入ets文件夹下的任意位置。
36
37  Image组件引入本地图片路径,即可显示图片(根目录为ets文件夹)。不支持跨包、跨模块调用该Image组件。
38
39  ```ts
40  Image('images/view.jpg')
41  .width(200)
42  ```
43
44  加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。
45
46- 网络资源
47
48  引入网络图片需申请权限ohos.permission.INTERNET,具体申请方式请参考[声明权限](../security/AccessToken/declare-permissions.md)。此时,Image组件的src参数为网络图片的链接。
49
50  当前Image组件仅支持加载简单网络图片。
51
52  Image组件首次加载网络图片时,需要请求网络资源,非首次加载时,默认从缓存中直接读取图片,更多图片缓存设置请参考[setImageCacheCount](../reference/apis-arkui/js-apis-system-app.md#setimagecachecount7)、[setImageRawDataCacheSize](../reference/apis-arkui/js-apis-system-app.md#setimagerawdatacachesize7)、[setImageFileCacheSize](../reference/apis-arkui/js-apis-system-app.md#setimagefilecachesize7)。但是,这三个图片缓存接口并不灵活,且后续不继续演进,对于复杂情况,更推荐使用[ImageKnife](https://gitcode.com/openharmony-tpc/ImageKnife)53
54  网络图片必须支持RFC 9113标准,否则会导致加载失败。如果下载的网络图片大于10MB或一次下载的网络图片数量较多,建议使用[HTTP](../network/http-request.md)工具提前预下载,提高图片加载性能,方便应用侧管理数据。
55
56  在显示网络图片时,Image 组件会将下载与缓存功能剥离至[缓存下载模块](../reference/apis-basic-services-kit/js-apis-request-cacheDownload.md)进行统一管理。缓存下载模块提供独立的预下载接口,允许应用开发者在创建Image组件前预下载所需图片。组件创建后,通过向缓存下载模块请求数据,从而优化了Image组件的显示流程。网络缓存的位置位于应用根目录下的cache目录中。
57
58  ```ts
59  Image('https://www.example.com/example.JPG') // 实际使用时请替换为真实地址
60  ```
61
62- Resource资源
63
64  使用资源格式可以跨包/跨模块引入图片,resources文件夹下的图片都可以通过$r资源接口读取到并转换到Resource格式。
65
66  **图1** resources  
67
68  ![image-resource](figures/image-resource.jpg)
69
70  调用方式:
71
72  ```
73  Image($r('app.media.icon'))
74  ```
75
76  还可以将图片放在rawfile文件夹下。
77
78  **图2** rawfile  
79
80  ![image-rawfile](figures/image-rawfile.jpg)
81
82  调用方式:
83
84  ```
85  Image($rawfile('example1.png'))
86  ```
87
88- 媒体库file://data/storage
89
90  支持file://路径前缀的字符串,用于访问通过[选择器](../reference/apis-core-file-kit/js-apis-file-picker.md)提供的图片路径。
91
92  1. 调用接口获取图库的照片url。
93
94      ```ts
95      import { photoAccessHelper } from '@kit.MediaLibraryKit';
96      import { BusinessError } from '@kit.BasicServicesKit';
97
98      @Entry
99      @Component
100      struct Index {
101        @State imgDatas: string[] = [];
102        // 获取照片url集
103        getAllImg() {
104          try {
105            let photoSelectOptions:photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
106            photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
107            photoSelectOptions.maxSelectNumber = 5;
108            let photoPicker:photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
109            photoPicker.select(photoSelectOptions).then((PhotoSelectResult:photoAccessHelper.PhotoSelectResult) => {
110              this.imgDatas = PhotoSelectResult.photoUris;
111              console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
112            }).catch((err:Error) => {
113              let message = (err as BusinessError).message;
114              let code = (err as BusinessError).code;
115              console.error(`PhotoViewPicker.select failed with. Code: ${code}, message: ${message}`);
116            });
117          } catch (err) {
118            let message = (err as BusinessError).message;
119            let code = (err as BusinessError).code;
120            console.error(`PhotoViewPicker failed with. Code: ${code}, message: ${message}`);    }
121        }
122
123        // aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
124        async aboutToAppear() {
125          this.getAllImg();
126        }
127        // 使用imgDatas的url加载图片。
128        build() {
129          Column() {
130            Grid() {
131              ForEach(this.imgDatas, (item:string) => {
132                GridItem() {
133                  Image(item)
134                    .width(200)
135                }
136              }, (item:string):string => JSON.stringify(item))
137            }
138          }.width('100%').height('100%')
139        }
140      }
141      ```
142
143  2. 从媒体库获取的url格式通常如下。
144
145      ```ts
146      Image('file://media/Photos/5')
147      .width(200)
148      ```
149
150
151- base64
152
153  路径格式为data:image/[png|jpeg|bmp|webp|heif];base64,[base64 data],其中[base64 data]为Base64字符串数据。
154
155  Base64格式字符串可用于存储图片的像素数据,在网页上使用较为广泛。
156
157
158### 多媒体像素图
159
160PixelMap是图片解码后的像素图,具体用法请参考[图片开发指导](../media/image/image-overview.md)。以下示例将加载的网络图片返回的数据解码成PixelMap格式,再显示在Image组件上。
161
162
163   ```ts
164   import { http } from '@kit.NetworkKit';
165   import { image } from '@kit.ImageKit';
166   import { BusinessError } from '@kit.BasicServicesKit';
167
168   @Entry
169   @Component
170   struct HttpExample {
171     outData: http.HttpResponse | undefined = undefined;
172     code: http.ResponseCode | number | undefined = undefined;
173     @State image: PixelMap | undefined = undefined; //创建PixelMap状态变量。
174
175     aboutToAppear(): void {
176       http.createHttp().request('https://www.example.com/xxx.png', //请填写一个具体的网络图片地址。
177         (error: BusinessError, data: http.HttpResponse) => {
178           if (error) {
179             console.error(`hello http request failed with. Code: ${error.code}, message: ${error.message}`);
180             return;
181           }
182           this.outData = data;
183           //将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
184           if (http.ResponseCode.OK === this.outData.responseCode) {
185             let imageData: ArrayBuffer = this.outData.result as ArrayBuffer;
186             let imageSource: image.ImageSource = image.createImageSource(imageData);
187             let options: image.DecodingOptions = {
188               'desiredPixelFormat': image.PixelMapFormat.RGBA_8888,
189             };
190             imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
191               this.image = pixelMap;
192             });
193           }
194         })
195     }
196
197     build() {
198       Column() {
199         //显示图片
200         Image(this.image)
201           .height(100)
202           .width(100)
203       }
204     }
205   }
206   ```
207
208### 可绘制描述符
209
210DrawableDescriptor是ArkUI提供的一种高级图片抽象机制,它通过将图片资源封装为可编程对象,实现了传统Image组件难以实现的动态组合与运行时控制功能。开发者可利用它实现图片的分层叠加(如徽章图标)、动态属性调整(如颜色滤镜)、复杂动画序列等高级效果,适用于需要灵活控制图片展现或实现复杂视觉交互的场景。详细使用方法,请参考[DrawableDescriptor](../../application-dev/reference/apis-arkui/js-apis-arkui-drawableDescriptor.md)。
211
212通过DrawableDescriptor显示图片及动画的示例如下所示:
213
214```ts
215import {
216  DrawableDescriptor,
217  PixelMapDrawableDescriptor,
218  LayeredDrawableDescriptor,
219  AnimatedDrawableDescriptor,
220  AnimationOptions
221} from '@kit.ArkUI';
222import { image } from '@kit.ImageKit';
223
224@Entry
225@Component
226struct Index {
227  // 声明DrawableDescriptor对象
228  @State pixmapDesc: DrawableDescriptor | null = null;
229  @State pixelMapDesc: PixelMapDrawableDescriptor | null = null;
230  @State layeredDesc: LayeredDrawableDescriptor | null = null;
231  @State animatedDesc: AnimatedDrawableDescriptor | null = null;
232  // 动画配置
233  private animationOptions: AnimationOptions = {
234    duration: 3000,
235    iterations: -1
236  };
237
238  async aboutToAppear() {
239    const resManager = this.getUIContext().getHostContext()?.resourceManager;
240    if (!resManager) {
241      return;
242    }
243    // 创建普通DrawableDescriptor
244    let pixmapDescResult = resManager.getDrawableDescriptor($r('app.media.landscape').id);
245    if (pixmapDescResult) {
246      this.pixmapDesc = pixmapDescResult as DrawableDescriptor;
247    }
248    // 创建PixelMapDrawableDescriptor
249    const pixelMap = await this.getPixmapFromMedia($r('app.media.landscape'));
250    this.pixelMapDesc = new PixelMapDrawableDescriptor(pixelMap);
251    // 创建分层图标
252    const foreground = await this.getDrawableDescriptor($r('app.media.foreground'));
253    const background = await this.getDrawableDescriptor($r('app.media.landscape'));
254    this.layeredDesc = new LayeredDrawableDescriptor(foreground, background);
255    // 创建动画图片(需加载多张图片)
256    const frame1 = await this.getPixmapFromMedia($r('app.media.sky'));
257    const frame2 = await this.getPixmapFromMedia($r('app.media.landscape'));
258    const frame3 = await this.getPixmapFromMedia($r('app.media.clouds'));
259    if (frame1 && frame2 && frame3) {
260      this.animatedDesc = new AnimatedDrawableDescriptor([frame1, frame2, frame3], this.animationOptions);
261    }
262  }
263
264  // 辅助方法:从资源获取PixelMap
265  private async getPixmapFromMedia(resource: Resource): Promise<image.PixelMap | undefined> {
266    const unit8Array = await this.getUIContext().getHostContext()?.resourceManager.getMediaContent(resource.id);
267    if (!unit8Array) {
268      return undefined;
269    }
270    const imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength));
271    const pixelMap = await imageSource.createPixelMap({
272      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
273    });
274    await imageSource.release();
275    return pixelMap;
276  }
277
278  // 辅助方法:获取DrawableDescriptor
279  private async getDrawableDescriptor(resource: Resource): Promise<DrawableDescriptor | undefined> {
280    const resManager = this.getUIContext().getHostContext()?.resourceManager;
281    if (!resManager) {
282      return undefined;
283    }
284    return (resManager.getDrawableDescriptor(resource.id)) as DrawableDescriptor;
285  }
286
287  build() {
288    RelativeContainer() {
289      Column() {
290
291        // 显示普通图片
292        Image(this.pixmapDesc)
293          .width(100)
294          .height(100)
295          .border({ width: 1, color: Color.Black })
296        // 显示PixelMap图片
297        Image(this.pixelMapDesc)
298          .width(100)
299          .height(100)
300          .border({ width: 1, color: Color.Red })
301        // 显示分层图标
302        if (this.layeredDesc) {
303          Image(this.layeredDesc)
304            .width(100)
305            .height(100)
306            .border({ width: 1, color: Color.Blue })
307        }
308        // 显示动画图片
309        if (this.animatedDesc) {
310          Image(this.animatedDesc)
311            .width(200)
312            .height(200)
313            .margin({ top: 20 })
314        }
315      }
316    }
317    .height('100%')
318    .width('100%')
319    .margin(50)
320  }
321}
322```
323
324![drawableDescriptor](figures/drawableDescriptor.gif)
325
326
327## 显示矢量图
328
329Image组件可显示矢量图(SVG格式的图片),SVG标签文档请参考[SVG标签说明](../../application-dev/reference/apis-arkui/arkui-ts/ts-basic-svg.md)。
330
331如果SVG图片没有原始大小,需要给Image组件设置宽高,否则不显示。SVG图片不支持通过image标签引用SVG格式和gif格式的本地其他图片。
332
333SVG格式的图片可以使用fillColor属性改变图片的绘制颜色。
334
335
336```ts
337Image($r('app.media.cloud'))
338  .width(50)
339  .fillColor(Color.Blue)
340```
341
342  **图3** 原始图片  
343
344![屏幕截图_20230223_141141](figures/屏幕截图_20230223_141141.png)
345
346  **图4** 设置绘制颜色后的SVG图片  
347
348![屏幕截图_20230223_141404](figures/屏幕截图_20230223_141404.png)
349
350### 矢量图引用位图
351
352如果Image加载的SVG图源中包含对本地位图的引用,则SVG图源的路径应当设置为以ets为根目录的工程路径,同时,本地位图的路径应设置为与SVG图源同级的相对路径。
353
354Image加载的SVG图源路径设置方法如下所示:
355
356```ts
357Image("images/icon.svg")
358  .width(50)
359  .height(50)
360```
361SVG图源通过`<image>`标签的`xlink:href`属性指定本地位图路径,本地位图路径设置为跟SVG图源同级的相对路径:
362
363```
364<svg width="200" height="200">
365  <image width="200" height="200" xlink:href="sky.png"></image>
366</svg>
367```
368文件工程路径示例如图:
369
370![image path](figures/imagePath.png)
371
372## 添加属性
373
374给Image组件设置属性可以使图片显示更灵活,达到一些自定义的效果。以下是几个常用属性的使用示例,完整属性信息详见[Image](../reference/apis-arkui/arkui-ts/ts-basic-components-image.md)。
375
376### 设置图片缩放类型
377
378通过设置objectFit属性,可以使图片在高度和宽度确定的框内进行缩放。
379
380
381```ts
382@Entry
383@Component
384struct MyComponent {
385  scroller: Scroller = new Scroller();
386
387  build() {
388    Scroll(this.scroller) {
389      Column() {
390        Row() {
391          Image($r('app.media.img_2'))
392            .width(200)
393            .height(150)
394            .border({ width: 1 })
395              // 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
396            .objectFit(ImageFit.Contain)
397            .margin(15)
398            .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
399          Image($r('app.media.ic_img_2'))
400            .width(200)
401            .height(150)
402            .border({ width: 1 })
403              // 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
404            .objectFit(ImageFit.Cover)
405            .margin(15)
406            .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
407          Image($r('app.media.img_2'))
408            .width(200)
409            .height(150)
410            .border({ width: 1 })
411              // 自适应显示。
412            .objectFit(ImageFit.Auto)
413            .margin(15)
414            .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
415        }
416
417        Row() {
418          Image($r('app.media.img_2'))
419            .width(200)
420            .height(150)
421            .border({ width: 1 })
422              // 不保持宽高比进行放大缩小,使得图片充满显示边界。
423            .objectFit(ImageFit.Fill)
424            .margin(15)
425            .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
426          Image($r('app.media.img_2'))
427            .width(200)
428            .height(150)
429            .border({ width: 1 })
430              // 保持宽高比显示,图片缩小或者保持不变。
431            .objectFit(ImageFit.ScaleDown)
432            .margin(15)
433            .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
434          Image($r('app.media.img_2'))
435            .width(200)
436            .height(150)
437            .border({ width: 1 })
438              // 保持原有尺寸显示。
439            .objectFit(ImageFit.None)
440            .margin(15)
441            .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
442        }
443      }
444    }
445  }
446}
447```
448
449![zh-cn_image_0000001622804833](figures/zh-cn_image_0000001622804833.png)
450
451
452### 图片插值
453
454当原图分辨率较低并放大显示时,图片会变得模糊并出现锯齿。这时可以使用interpolation属性对图片进行插值,以提高显示清晰度。
455
456
457```ts
458@Entry
459@Component
460struct Index {
461  build() {
462    Column() {
463      Row() {
464        Image($r('app.media.grass'))
465          .width('40%')
466          .interpolation(ImageInterpolation.None)
467          .borderWidth(1)
468          .overlay("Interpolation.None", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
469          .margin(10)
470        Image($r('app.media.grass'))
471          .width('40%')
472          .interpolation(ImageInterpolation.Low)
473          .borderWidth(1)
474          .overlay("Interpolation.Low", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
475          .margin(10)
476      }.width('100%')
477      .justifyContent(FlexAlign.Center)
478
479      Row() {
480        Image($r('app.media.grass'))
481          .width('40%')
482          .interpolation(ImageInterpolation.Medium)
483          .borderWidth(1)
484          .overlay("Interpolation.Medium", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
485          .margin(10)
486        Image($r('app.media.grass'))
487          .width('40%')
488          .interpolation(ImageInterpolation.High)
489          .borderWidth(1)
490          .overlay("Interpolation.High", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
491          .margin(10)
492      }.width('100%')
493      .justifyContent(FlexAlign.Center)
494    }
495    .height('100%')
496  }
497}
498```
499
500![zh-cn_image_0000001643127365](figures/zh-cn_image_0000001643127365.png)
501
502
503### 设置图片重复样式
504
505通过objectRepeat属性设置图片的重复样式方式,重复样式请参考[ImageRepeat](../reference/apis-arkui/arkui-ts/ts-appendix-enums.md#imagerepeat)枚举说明。
506
507
508```ts
509@Entry
510@Component
511struct MyComponent {
512  build() {
513    Column({ space: 10 }) {
514      Row({ space: 5 }) {
515        Image($r('app.media.ic_public_favor_filled_1'))
516          .width(110)
517          .height(115)
518          .border({ width: 1 })
519          .objectRepeat(ImageRepeat.XY)
520          .objectFit(ImageFit.ScaleDown)
521          // 在水平轴和竖直轴上同时重复绘制图片
522          .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
523        Image($r('app.media.ic_public_favor_filled_1'))
524          .width(110)
525          .height(115)
526          .border({ width: 1 })
527          .objectRepeat(ImageRepeat.Y)
528          .objectFit(ImageFit.ScaleDown)
529          // 只在竖直轴上重复绘制图片
530          .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
531        Image($r('app.media.ic_public_favor_filled_1'))
532          .width(110)
533          .height(115)
534          .border({ width: 1 })
535          .objectRepeat(ImageRepeat.X)
536          .objectFit(ImageFit.ScaleDown)
537          // 只在水平轴上重复绘制图片
538          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
539      }
540    }.height(150).width('100%').padding(8)
541  }
542}
543```
544
545![zh-cn_image_0000001593444112](figures/zh-cn_image_0000001593444112.png)
546
547
548### 设置图片渲染模式
549
550通过renderMode属性设置图片的渲染模式为原色或黑白。
551
552
553```ts
554@Entry
555@Component
556struct MyComponent {
557  build() {
558    Column({ space: 10 }) {
559      Row({ space: 50 }) {
560        Image($r('app.media.example'))
561          // 设置图片的渲染模式为原色
562          .renderMode(ImageRenderMode.Original)
563          .width(100)
564          .height(100)
565          .border({ width: 1 })
566            // overlay是通用属性,用于在组件上显示说明文字
567          .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
568        Image($r('app.media.example'))
569          // 设置图片的渲染模式为黑白
570          .renderMode(ImageRenderMode.Template)
571          .width(100)
572          .height(100)
573          .border({ width: 1 })
574          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
575      }
576    }.height(150).width('100%').padding({ top: 20,right: 10 })
577  }
578}
579```
580
581![zh-cn_image_0000001593293100](figures/zh-cn_image_0000001593293100.png)
582
583
584### 设置图片解码尺寸
585
586通过sourceSize属性设置图片解码尺寸,降低图片的分辨率。
587
588原图尺寸为1280×960,该示例将图片解码为40×40和90×90两个尺寸。
589
590
591```ts
592@Entry
593@Component
594struct Index {
595  build() {
596    Column() {
597      Row({ space: 50 }) {
598        Image($r('app.media.example'))
599          .sourceSize({
600            width: 40,
601            height: 40
602          })
603          .objectFit(ImageFit.ScaleDown)
604          .aspectRatio(1)
605          .width('25%')
606          .border({ width: 1 })
607          .overlay('width:40 height:40', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
608        Image($r('app.media.example'))
609          .sourceSize({
610            width: 90,
611            height: 90
612          })
613          .objectFit(ImageFit.ScaleDown)
614          .width('25%')
615          .aspectRatio(1)
616          .border({ width: 1 })
617          .overlay('width:90 height:90', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
618      }.height(150).width('100%').padding(20)
619    }
620  }
621}
622```
623
624![zh-cn_image_0000001593769844](figures/zh-cn_image_0000001593769844.png)
625
626
627### 为图片添加滤镜效果
628
629通过colorFilter调整图片的像素颜色,为图片添加滤镜。
630
631
632```ts
633@Entry
634@Component
635struct Index {
636  build() {
637    Column() {
638      Row() {
639        Image($r('app.media.example'))
640          .width('40%')
641          .margin(10)
642        Image($r('app.media.example'))
643          .width('40%')
644          .colorFilter(
645            [1, 1, 0, 0, 0,
646             0, 1, 0, 0, 0,
647             0, 0, 1, 0, 0,
648             0, 0, 0, 1, 0])
649          .margin(10)
650      }.width('100%')
651      .justifyContent(FlexAlign.Center)
652    }
653  }
654}
655```
656
657![zh-cn_image_0000001643171357](figures/zh-cn_image_0000001643171357.png)
658
659
660### 同步加载图片
661
662一般情况下,图片加载流程会异步进行,以避免阻塞主线程,影响UI交互。但是特定情况下,图片刷新时会出现闪烁,这时可以使用syncLoad属性,使图片同步加载,从而避免出现闪烁。不建议图片加载较长时间时使用,会导致页面无法响应。
663
664
665```ts
666Image($r('app.media.icon'))
667  .syncLoad(true)
668```
669
670
671## 事件调用
672
673通过在Image组件上绑定onComplete事件,图片加载成功后可以获取图片的必要信息。如果图片加载失败,也可以通过绑定onError回调来获得结果。
674
675
676```ts
677@Entry
678@Component
679struct MyComponent {
680  @State widthValue: number = 0;
681  @State heightValue: number = 0;
682  @State componentWidth: number = 0;
683  @State componentHeight: number = 0;
684
685  build() {
686    Column() {
687      Row() {
688        Image($r('app.media.ic_img_2'))
689          .width(200)
690          .height(150)
691          .margin(15)
692          .onComplete(msg => {
693            if(msg){
694              this.widthValue = msg.width;
695              this.heightValue = msg.height;
696              this.componentWidth = msg.componentWidth;
697              this.componentHeight = msg.componentHeight;
698            }
699          })
700            // 图片获取失败,打印结果
701          .onError(() => {
702            console.info('load image fail')
703          })
704          .overlay('\nwidth: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '\ncomponentWidth: ' + String(this.componentWidth) + '\ncomponentHeight: ' + String(this.componentHeight), {
705            align: Alignment.Bottom,
706            offset: { x: 0, y: 60 }
707          })
708      }
709    }
710  }
711}
712```
713
714![zh-cn_image_0000001511740460](figures/zh-cn_image_0000001511740460.png)
715
716## 相关实例
717
718针对显示图片开发,有以下相关实例可供参考:
719
720- [显示图片](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/ArkUISample/ImageComponent)