• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Image
2
3Image为图片组件,常用于在应用中显示图片。Image支持加载[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)、[ResourceStr](ts-types.md#resourcestr)和[DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor)类型的数据源,支持png、jpg、jpeg、bmp、svg、webp、gif和heif类型的图片格式。
4
5> **说明:**
6>
7> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8>
9> 使用快捷组合键对Image组件复制时,Image组件必须处于[获焦状态](../../../ui/arkts-common-events-focus-event.md#设置组件是否可获焦)。Image组件默认不获焦,需将[focusable](ts-universal-attributes-focus.md#focusable)属性设置为true,即可使用TAB键将焦点切换到组件上,再将[focusOnTouch](ts-universal-attributes-focus.md#focusontouch9)属性设置为true,即可实现点击获焦。
10>
11> 图片格式支持SVG图源,SVG标签文档请参考[SVG标签说明](./ts-basic-svg.md)
12>
13> 动图在Image组件不可见时停止动画,通过[onVisibleAreaChange](./ts-universal-component-visible-area-change-event.md#onvisibleareachange)事件实现组件的可见状态,可见阈值ratios大于0时,Image可见。
14
15## 需要权限
16
17使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[声明权限](../../../security/AccessToken/declare-permissions.md)。
18
19
20## 子组件
21
2223
24
25## 接口
26
27### Image
28
29Image(src: PixelMap | ResourceStr | DrawableDescriptor)
30
31通过图片数据源获取图片,用于后续渲染展示。
32
33Image组件加载图片失败或图片尺寸为0时,图片组件大小自动为0,不跟随父组件的布局约束。
34
35Image组件默认按照居中裁剪,例如组件宽高设置相同,原图长宽不等,此时按照中间区域进行裁剪。
36
37Image加载成功且组件不设置宽高时,其显示大小自适应父组件。
38
39**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
40
41**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
42
43**系统能力:** SystemCapability.ArkUI.ArkUI.Full
44
45**参数:**
46
47| 参数名  | 类型                                     | 必填   | 说明                                     |
48| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
49| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr)\|&nbsp;[DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是    | 图片的数据源,支持本地图片和网络图片,引用方式请参考[加载图片资源](../../../ui/arkts-graphics-display.md#加载图片资源)。<br>1. PixelMap格式为像素图,常用于图片编辑的场景。<br>2. ResourceStr包含Resource和string格式。<br>string格式可用于加载网络图片和本地图片,常用于加载网络图片。当使用相对路径引用本地图片时,例如Image("common/test.jpg"),不支持跨包/跨模块调用该Image组件,建议使用Resource格式来管理需全局使用的图片资源。<br>- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。<br>- 支持file://路径前缀的字符串,[应用沙箱URI](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10):file://\<bundleName>/\<sandboxPath>。当访问的路径中包含特殊符号时,需要使用[fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath)去做转换。同时需要保证目录包路径下的文件有可读权限。<br>Resource格式可以跨包/跨模块访问资源文件,是访问本地图片的推荐方式。<br/>3. 当传入资源id或name为普通图片时,生成DrawableDescriptor对象。传入[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)类型可播放PixelMap数组动画。<br>**说明:**<br/>- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。<br/>- ArkTS卡片上不支持http:/\/等网络相关路径前缀和file:/\/路径前缀的字符串。<br/>- ArkTS卡片上不支持&nbsp;[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)类型。 <br/>- 加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。<br/>- 网络图片必须支持RFC 9113标准,否则会导致加载失败。<br/>- 如果下载的网络图片大于10MB或一次下载的网络图片数量较多,建议使用[HTTP](../../../network/http-request.md)工具提前预下载,提高图片加载性能,方便应用侧管理数据。<br/> - Image直接传入URL可能会带来的潜在性能问题,例如:(1) 大图加载时无法提前下载,白块显示的时间较长;(2) 小图设置同步加载,在弱网环境下,可能会阻塞UI线程造成冻屏问题;(3) 在快速滑动的瀑布流中,无法提前对即将要显示的图片进行下载,导致滑动白块较多;不同场景下,性能问题会有不同的表现,建议将网络下载部分与Image的显示剥离,可提前下载或者异步下载。<br/>- 如果SVG图片没有原生大小,需要给Image组件设置宽高,否则不显示。<br/>- 如果SVG图片通过image标签引用本地其他图片,被引用的图片不支持svg格式和gif格式。<br/>- src由有效切换为无效时,图片保持不动。 |
50
51### Image<sup>12+</sup>
52
53Image(src: PixelMap | ResourceStr | DrawableDescriptor | ImageContent)
54
55src新增[ImageContent](#imagecontent12)类型,可指定对应的图形内容。
56
57**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
58
59**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
60
61**系统能力:** SystemCapability.ArkUI.ArkUI.Full
62
63**参数:**
64
65| 参数名  | 类型                                     | 必填   | 说明                                     |
66| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
67| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr)\|&nbsp;[DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor)\|&nbsp;[ImageContent](#imagecontent12) | 是    | 图片的数据源,支持本地图片和网络图片,引用方式请参考[加载图片资源](../../../ui/arkts-graphics-display.md#加载图片资源)。<br>1. PixelMap格式为像素图,常用于图片编辑的场景。<br>2. ResourceStr包含Resource和string格式。<br>string格式可用于加载网络图片和本地图片,常用于加载网络图片。当使用相对路径引用本地图片时,例如Image("common/test.jpg"),不支持跨包/跨模块调用该Image组件,建议使用Resource格式来管理需全局使用的图片资源。<br>- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。<br>- 支持file://路径前缀的字符串,[应用沙箱URI](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10):file://\<bundleName>/\<sandboxPath>。当访问的路径中包含特殊符号时,需要使用[fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath)去做转换。同时需要保证目录包路径下的文件有可读权限。<br>Resource格式可以跨包/跨模块访问资源文件,是访问本地图片的推荐方式。<br/>3. 当传入资源id或name为普通图片时,生成DrawableDescriptor对象。传入[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)类型可播放PixelMap数组动画。<br>4. 传入[ImageContent](#imagecontent12)类型,指定图像内容。<br>**说明:**<br/>- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。<br/>- ArkTS卡片上不支持http:/\/等网络相关路径前缀和file:/\/路径前缀的字符串。<br/>- ArkTS卡片上不支持&nbsp;[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)类型。 <br/>- 加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。<br/>- 网络图片必须支持RFC 9113标准,否则会导致加载失败。<br/>- 如果下载的网络图片大于10MB或一次下载的网络图片数量较多,建议使用[HTTP](../../../network/http-request.md)工具提前预下载,提高图片加载性能,方便应用侧管理数据。<br/> - Image直接传入URL可能会带来的潜在性能问题,例如:(1) 大图加载时无法提前下载,白块显示的时间较长;(2) 小图设置同步加载,在弱网环境下,可能会阻塞UI线程造成冻屏问题;(3) 在快速滑动的瀑布流中,无法提前对即将要显示的图片进行下载,导致滑动白块较多;不同场景下,性能问题会有不同的表现,建议将网络下载部分与Image的显示剥离,可提前下载或者异步下载。<br/>- 如果SVG图片没有原生大小,需要给Image组件设置宽高,否则不显示。<br/>- 如果SVG图片通过image标签引用本地其他图片,被引用的图片不支持svg格式和gif格式。<br/>- src由有效切换为无效时,图片保持不动。 |
68
69### Image<sup>12+</sup>
70
71Image(src: PixelMap | ResourceStr | DrawableDescriptor, imageAIOptions: ImageAIOptions)
72
73Image新增[imageAIOptions](ts-image-common.md#imageaioptions)参数,为组件设置AI分析选项。
74
75**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
76
77**系统能力:** SystemCapability.ArkUI.ArkUI.Full
78
79**参数:**
80
81| 参数名  | 类型                                     | 必填   | 说明                                     |
82| ---- | ---------------------------------------- | ---- | ---------------------------------------- |
83| src  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr)\|&nbsp;[DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是    | 图片的数据源,支持本地图片和网络图片,引用方式请参考[加载图片资源](../../../ui/arkts-graphics-display.md#加载图片资源)。<br>1. PixelMap格式为像素图,常用于图片编辑的场景。<br>2. ResourceStr包含Resource和string格式。<br>string格式可用于加载网络图片和本地图片,常用于加载网络图片。当使用相对路径引用本地图片时,例如Image("common/test.jpg"),不支持跨包/跨模块调用该Image组件,建议使用Resource格式来管理需全局使用的图片资源。<br>- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。<br>- 支持file://路径前缀的字符串,[应用沙箱URI](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10):file://\<bundleName>/\<sandboxPath>。当访问的路径中包含特殊符号时,需要使用[fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath)去做转换。同时需要保证目录包路径下的文件有可读权限。<br>Resource格式可以跨包/跨模块访问资源文件,是访问本地图片的推荐方式。<br/>3. 当传入资源id或name为普通图片时,生成DrawableDescriptor对象。传入[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)类型可播放PixelMap数组动画。<br>**说明:**<br/>- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。<br/>- ArkTS卡片上不支持http:/\/等网络相关路径前缀和file:/\/路径前缀的字符串。<br/>- ArkTS卡片上不支持&nbsp;[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)类型。 <br/>- 加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。<br/>- 网络图片必须支持RFC 9113标准,否则会导致加载失败。<br/>- 如果下载的网络图片大于10MB或一次下载的网络图片数量较多,建议使用[HTTP](../../../network/http-request.md)工具提前预下载,提高图片加载性能,方便应用侧管理数据。<br/> - Image直接传入URL可能会带来的潜在性能问题,例如:(1) 大图加载时无法提前下载,白块显示的时间较长;(2) 小图设置同步加载,在弱网环境下,可能会阻塞UI线程造成冻屏问题;(3) 在快速滑动的瀑布流中,无法提前对即将要显示的图片进行下载,导致滑动白块较多;不同场景下,性能问题会有不同的表现,建议将网络下载部分与Image的显示剥离,可提前下载或者异步下载。<br/>- 如果SVG图片没有原生大小,需要给Image组件设置宽高,否则不显示。<br/>- 如果SVG图片通过image标签引用本地其他图片,被引用的图片不支持svg格式和gif格式。<br/>- src由有效切换为无效时,图片保持不动。 |
84| imageAIOptions  | [ImageAIOptions](ts-image-common.md#imageaioptions) | 是   | 给组件设置一个AI分析选项,通过此项可配置分析类型或绑定一个分析控制器。 |
85
86## 属性
87
88属性的详细使用指导请参考[添加属性](../../../ui/arkts-graphics-display.md#添加属性)。除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
89
90> **说明:**
91>
92> Image组件不支持设置通用属性[foregroundColor](./ts-universal-attributes-foreground-color.md#foregroundcolor),可以通过Image组件的[fillColor](#fillcolor)属性设置填充颜色。
93
94### alt
95
96alt(value:&nbsp;string&nbsp;|&nbsp;Resource &nbsp;|&nbsp;PixelMap)
97
98设置图片加载时显示的占位图。
99
100当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
101
102**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
103
104**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
105
106**系统能力:** SystemCapability.ArkUI.ArkUI.Full
107
108**参数:**
109
110| 参数名 | 类型                                                     | 必填 | 说明                                                         |
111| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
112| value  | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)&nbsp;\|&nbsp;[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)<sup>12+</sup> | 是   | 加载时显示的占位图,支持本地图片(png、jpg、bmp、svg、gif和heif类型),支持[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)类型图片,不支持网络图片。<br/>默认值:null |
113
114### objectFit
115
116objectFit(value: ImageFit)
117
118设置图片的填充效果。
119
120**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
121
122**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
123
124**系统能力:** SystemCapability.ArkUI.ArkUI.Full
125
126**参数:**
127
128| 参数名 | 类型                                      | 必填 | 说明                                        |
129| ------ | ----------------------------------------- | ---- | ------------------------------------------- |
130| value  | [ImageFit](ts-appendix-enums.md#imagefit) | 是   | 图片的填充效果。<br/>默认值:ImageFit.Cover |
131
132### objectRepeat
133
134objectRepeat(value: ImageRepeat)
135
136设置图片的重复样式,从中心点向两边重复,剩余空间不足放下一张图片时会截断。svg类型图源不支持该属性。
137
138当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
139
140**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
141
142**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
143
144**系统能力:** SystemCapability.ArkUI.ArkUI.Full
145
146**参数:**
147
148| 参数名 | 类型                                            | 必填 | 说明                                              |
149| ------ | ----------------------------------------------- | ---- | ------------------------------------------------- |
150| value  | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 是   | 图片的重复样式。<br/>默认值:ImageRepeat.NoRepeat |
151
152### interpolation
153
154interpolation(value: ImageInterpolation)
155
156设置图片的插值效果,即缓解图片在缩放时的锯齿问题。svg类型图源不支持该属性。
157
158当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
159
160**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
161
162**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
163
164**系统能力:** SystemCapability.ArkUI.ArkUI.Full
165
166**参数:**
167
168| 参数名 | 类型                                      | 必填 | 说明                                                |
169| ------ | ----------------------------------------- | ---- | --------------------------------------------------- |
170| value  | [ImageInterpolation](#imageinterpolation) | 是   | 图片的插值效果。<br/>默认值:ImageInterpolation.Low |
171
172### renderMode
173
174renderMode(value: ImageRenderMode)
175
176设置图片的渲染模式。svg类型图源不支持该属性。
177
178设置 [ColorFilter](#colorfilter9) 时,该属性设置不生效。
179
180当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
181
182**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
183
184**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
185
186**系统能力:** SystemCapability.ArkUI.ArkUI.Full
187
188**参数:**
189
190| 参数名 | 类型                                | 必填 | 说明                                                         |
191| ------ | ----------------------------------- | ---- | ------------------------------------------------------------ |
192| value  | [ImageRenderMode](#imagerendermode) | 是   | 图片的渲染模式为原色或黑白。<br/>默认值:ImageRenderMode.Original |
193
194### sourceSize
195
196sourceSize(value: { width:&nbsp;number;&nbsp;height:&nbsp;number&nbsp;})
197
198设置图片解码尺寸。仅在目标尺寸小于图源尺寸时生效。svg类型图源和PixelMap资源不支持该属性。
199
200当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
201
202**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
203
204**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
205
206**系统能力:** SystemCapability.ArkUI.ArkUI.Full
207
208**参数:**
209
210| 参数名 | 类型                                                    | 必填 | 说明                                                         |
211| ------ | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
212| value  | {<br/>width:&nbsp;number,<br/>height:&nbsp;number<br/>} | 是   | 图片解码尺寸,降低图片的分辨率,常用于需要让图片显示尺寸比组件尺寸更小的场景。和ImageFit.None配合使用时可在组件内显示小图。<br/>单位:vp |
213
214### matchTextDirection
215
216matchTextDirection(value: boolean)
217
218设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
219
220当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
221
222**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
223
224**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
225
226**系统能力:** SystemCapability.ArkUI.ArkUI.Full
227
228**参数:**
229
230| 参数名 | 类型    | 必填 | 说明                                         |
231| ------ | ------- | ---- | -------------------------------------------- |
232| value  | boolean | 是   | 图片是否跟随系统语言方向。<br/>默认值:false |
233
234### fitOriginalSize
235
236fitOriginalSize(value: boolean)
237
238设置图片的显示尺寸是否跟随图源尺寸。图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
239
240当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
241
242**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
243
244**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
245
246**系统能力:** SystemCapability.ArkUI.ArkUI.Full
247
248**参数:**
249
250| 参数名 | 类型    | 必填 | 说明                                             |
251| ------ | ------- | ---- | ------------------------------------------------ |
252| value  | boolean | 是   | 图片的显示尺寸是否跟随图源尺寸<br/>默认值:false |
253
254### fillColor
255
256fillColor(value: ResourceColor)
257
258设置填充颜色,设置后填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片中所有可绘制元素的填充颜色。如需对png图片进行修改颜色,可以使用[colorFilter](#colorfilter9)。
259
260当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
261
262**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
263
264**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
265
266**系统能力:** SystemCapability.ArkUI.ArkUI.Full
267
268**参数:**
269
270| 参数名 | 类型                                       | 必填 | 说明           |
271| ------ | ------------------------------------------ | ---- | -------------- |
272| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 设置填充颜色。 |
273
274### autoResize
275
276autoResize(value: boolean)
277
278设置图片解码过程中是否对图源自动缩放。降采样解码时图片的部分信息丢失,因此可能会导致图片质量的下降(如:出现锯齿),这时可以选择把autoResize设为false,按原图尺寸解码,提升显示效果,但会增加内存占用。
279
280原图尺寸和显示尺寸不匹配时,图片都会出现些许的失真、模糊。最佳清晰度配置建议:
281
282图片缩小显示时:.autoResize(false) + .interpolation(.Medium)
283
284图片放大显示时:.interpolation(.High)
285
286当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
287
288**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
289
290**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
291
292**系统能力:** SystemCapability.ArkUI.ArkUI.Full
293
294**参数:**
295
296| 参数名 | 类型    | 必填 | 说明                                                         |
297| ------ | ------- | ---- | ------------------------------------------------------------ |
298| value  | boolean | 是   | 图片解码过程中是否对图源自动缩放。设置为true时,组件会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。如原图大小为1920x1080,而显示区域大小为200x200,则图片会降采样解码到200x200的尺寸,大幅度节省图片占用的内存。<br/>默认值:false |
299
300### syncLoad<sup>8+</sup>
301
302syncLoad(value: boolean)
303
304设置是否同步加载图片。建议加载尺寸较小的本地图片时将syncLoad设为true,因为耗时较短,在主线程上执行即可。
305
306当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
307
308**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
309
310**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
311
312**系统能力:** SystemCapability.ArkUI.ArkUI.Full
313
314**参数:**
315
316| 参数名 | 类型    | 必填 | 说明                                                         |
317| ------ | ------- | ---- | ------------------------------------------------------------ |
318| value  | boolean | 是   | 是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。<br/>默认值:false |
319
320### copyOption<sup>9+</sup>
321
322copyOption(value: CopyOptions)
323
324设置图片是否可复制。当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。svg图片不支持复制。
325
326当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
327
328**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
329
330**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
331
332**系统能力:** SystemCapability.ArkUI.ArkUI.Full
333
334**参数:**
335
336| 参数名 | 类型                                             | 必填 | 说明                                          |
337| ------ | ------------------------------------------------ | ---- | --------------------------------------------- |
338| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 是   | 图片是否可复制。<br/>默认值:CopyOptions.None |
339
340### colorFilter<sup>9+</sup>
341
342colorFilter(value: ColorFilter | DrawingColorFilter)
343
344为图像设置颜色滤镜效果。
345
346设置该属性时,[renderMode](#rendermode)属性设置不生效。
347
348**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
349
350**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
351
352**系统能力:** SystemCapability.ArkUI.ArkUI.Full
353
354**参数:**
355
356| 参数名 | 类型                                    | 必填 | 说明                                                         |
357| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
358| value  | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter)<sup>12+</sup> | 是   | 1. 给图像设置颜色滤镜效果,入参为一个的4x5的RGBA转换矩阵。<br/>矩阵第一行表示R(红色)的向量值,第二行表示G(绿色)的向量值,第三行表示B(蓝色)的向量值,第四行表示A(透明度)的向量值,4行分别代表不同的RGBA的向量值。<br/>当矩阵对角线值为1,其余值为0时,保持图片原有色彩。<br/> **计算规则:**<br/>如果输入的滤镜矩阵为:<br/>![image-matrix-1](figures/image-matrix-1.jpg)<br/>像素点为[R, G, B, A]<br/>则过滤后的颜色为 [R’, G’, B’, A’]<br/>![image-matrix-2](figures/image-matrix-2.jpg)<br/>2. 从API Version12开始支持@ohos.graphics.drawing的ColorFilter类型作为入参。<br/>**说明:** <br/>API Version 11及之前,svg类型图源不支持该属性。<br/>从API version 12开始,该接口中的DrawingColorfilter类型支持在原子化服务中使用。其中,svg类型的图源需具有stroke属性。|
359
360### draggable<sup>9+</sup>
361
362draggable(value: boolean)
363
364设置组件默认拖拽效果。不能和[onDragStart](ts-universal-events-drag-drop.md#ondragstart)事件同时使用。
365
366**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
367
368**系统能力:** SystemCapability.ArkUI.ArkUI.Full
369
370**参数:**
371
372| 参数名 | 类型    | 必填 | 说明                                                         |
373| ------ | ------- | ---- | ------------------------------------------------------------ |
374| value  | boolean | 是   | 组件默认拖拽效果,设置为true时,组件可拖拽,绑定的长按手势不生效。<br />API version 9及之前,默认值为false。API version 10及之后,默认值为true。<br /> 若用户需要设置自定义手势,则需要将draggable设置为false。 |
375
376### enableAnalyzer<sup>11+</sup>
377
378enableAnalyzer(enable:&nbsp;boolean)
379
380设置组件支持AI分析,当前支持主体识别、文字识别和对象查找等功能。<!--RP3--><!--RP3End-->
381
382不能和[overlay](ts-universal-attributes-overlay.md)属性同时使用,两者同时设置时overlay中CustomBuilder属性将失效。该特性依赖设备能力。
383
384分析图像要求是静态非矢量图,即svg、gif等图像类型不支持分析,支持传入[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)进行分析,目前仅支持[RGBA_8888](../../apis-image-kit/js-apis-image.md#pixelmapformat7)类型,使用方式见[示例4](#示例4)。
385
386alt占位图不支持分析,objectRepeat属性仅在ImageRepeat.NoRepeat下支持分析,隐私遮罩属性[obscured](ts-universal-attributes-obscured.md)打开时不支持分析。
387
388基于完整原始图像进行分析,设置clip、margin、borderRadius、position和objectFit属性导致图像显示不完整,或使用renderMode设置蒙层,仍基于完整原始图像进行分析。 copyOption属性不影响AI分析功能。
389
390当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
391
392> **说明:**
393>
394> 需要配置权限:ohos.permission.INTERNET395
396**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
397
398**系统能力:** SystemCapability.ArkUI.ArkUI.Full
399
400**参数:**
401
402| 参数名 | 类型    | 必填 | 说明                                                         |
403| ------ | ------- | ---- | ------------------------------------------------------------ |
404| enable  | boolean | 是   | 组件支持AI分析,设置为true时,组件可进行AI分析。<br/>默认值:false |
405
406### resizable<sup>11+</sup>
407
408resizable(value: ResizableOptions)
409
410设置图像拉伸时可调整大小的图像选项。拉伸对拖拽缩略图以及占位图有效。
411
412设置合法的 [ResizableOptions](#resizableoptions11) 时,objectRepeat 属性设置不生效。
413
414当设置 top +bottom 大于原图的高或者 left + right 大于原图的宽时 [ResizableOptions](#resizableoptions11) 属性设置不生效。
415
416当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
417
418**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
419
420**系统能力:** SystemCapability.ArkUI.ArkUI.Full
421
422**参数:**
423
424| 参数名 | 类型                                    | 必填 | 说明                             |
425| ------ | --------------------------------------- | ---- | -------------------------------- |
426| value  | [ResizableOptions](#resizableoptions11) | 是   | 图像拉伸时可调整大小的图像选项。 |
427
428### privacySensitive<sup>12+</sup>
429
430privacySensitive(supported: boolean)
431
432设置是否支持卡片敏感隐私信息。
433
434**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
435
436**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
437
438**系统能力:** SystemCapability.ArkUI.ArkUI.Full
439
440**参数:**
441
442| 参数名    | 类型    | 必填 | 说明                     |
443| --------- | ------- | ---- | ------------------------ |
444| supported | boolean | 是   | 是否支持卡片敏感隐私信息。<br/>默认值为false,当设置为true时,隐私模式下图片将显示为半透明底板样式。<br/>**说明:** <br/>设置null则不敏感。<br/>进入隐私模式需要[卡片框架支持](./ts-universal-attributes-obscured.md)。 |
445
446### dynamicRangeMode<sup>12+</sup>
447
448dynamicRangeMode(value: DynamicRangeMode)
449
450设置期望展示的图像动态范围。
451
452<!--RP1--><!--RP1End-->
453
454**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
455
456**系统能力:** SystemCapability.ArkUI.ArkUI.Full
457
458**参数:**
459
460| 参数名 | 类型                                    | 必填 | 说明                             |
461| ------ | --------------------------------------- | ---- | -------------------------------- |
462| value  | [DynamicRangeMode](#dynamicrangemode12-1) | 是   | 图像显示的动态范围。<br/>默认值:dynamicRangeMode.Standard |
463
464## ImageContent<sup>12+</sup>
465
466指定图像内容。
467
468**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
469
470**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
471
472**系统能力:** SystemCapability.ArkUI.ArkUI.Full
473
474| 名称     | 说明                    |
475| ------ | -------------------------- |
476| EMPTY   | 空图像。                   |
477
478## ImageInterpolation
479
480**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
481
482**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
483
484**系统能力:** SystemCapability.ArkUI.ArkUI.Full
485
486| 名称     | 说明                       |
487| ------ | -------------------------- |
488| None   | 最近邻插值。                   |
489| High   | Cubic插值,插值质量最高,可能会影响图片渲染的速度。 |
490| Medium | MipMap插值。                     |
491| Low    | 双线性插值。                     |
492
493## ImageRenderMode
494
495**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
496
497**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
498
499**系统能力:** SystemCapability.ArkUI.ArkUI.Full
500
501| 名称     | 说明           |
502| -------- | -------------- |
503| Original | 原色渲染模式。 |
504| Template | 黑白渲染模式。 |
505
506## ResizableOptions<sup>11+</sup>
507
508图像拉伸时可调整大小的图像选项。
509
510**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
511
512**系统能力:** SystemCapability.ArkUI.ArkUI.Full
513
514| 名称 | 类型 | 必填 | 说明 |
515| --------- |-----------|-----------|-----------|
516| slice | [EdgeWidths](#edgewidths参数说明) |  否  | 边框宽度类型,用于描述组件边框不同方向的宽度。<br>**说明:**<br>只有当bottom和right同时大于0时,该属性生效。 |
517| lattice<sup>12+</sup> | [DrawingLattice](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#lattice12) |  否  | 矩形网格对象。<br>**说明:**<br> 通过@ohos.graphics.drawing的createImageLattice接口创建Lattice类型作为入参。将图像划分为矩形网格,同时处于偶数列和偶数行上的网格图像是固定的,不会被拉伸。<br>该参数对[backgroundImageResizable](ts-universal-attributes-background.md#backgroundimageresizable12)接口不生效。 |
518
519## EdgeWidths参数说明
520
521**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
522
523**系统能力:** SystemCapability.ArkUI.ArkUI.Full
524
525| 名称 | 类型 | 必填 | 说明 |
526| --------- |-----------|-----------|-----------|
527|  top    |  [Length](ts-types.md#length)  |  否  | 图片顶部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
528|  right  |  [Length](ts-types.md#length)  |  否  | 图片右部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
529|  bottom |  [Length](ts-types.md#length)  |  否  | 图片底部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
530|  left   |  [Length](ts-types.md#length)  |  否  | 图片左部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
531
532![edgewidths](figures/edgewidths.png)
533
534## DynamicRangeMode<sup>12+</sup>
535
536期望展示的图像动态范围。
537
538**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
539
540**系统能力:** SystemCapability.ArkUI.ArkUI.Full
541
542| 名称     | 值    | 说明                    |
543| ------ | -------------------------- | -------------------------- |
544| HIGH   | 0  | 不受限动态范围,最大限度进行图片提亮。              |
545| CONSTRAINT | 1 | 受限动态范围,受限进行图片提亮。          |
546| STANDARD | 2 | 标准动态范围,不进行图片提亮。         |
547
548## 事件
549
550除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
551
552### onComplete
553
554onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number }) =&gt; void)
555
556图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。
557
558当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
559
560**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
561
562**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
563
564**系统能力:** SystemCapability.ArkUI.ArkUI.Full
565
566**参数:**
567
568| 参数名                       | 类型   | 必填 | 说明                                                         |
569| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
570| width                        | number | 是   | 图片的宽。<br/>单位:像素                                    |
571| height                       | number | 是   | 图片的高。<br/>单位:像素                                    |
572| componentWidth               | number | 是   | 组件的宽。<br/>单位:像素                                    |
573| componentHeight              | number | 是   | 组件的高。<br/>单位:像素                                    |
574| loadingStatus                | number | 是   | 图片加载成功的状态值。<br/>**说明:**<br/>返回的状态值为0时,表示图片数据加载成功。返回的状态值为1时,表示图片解码成功。 |
575| contentWidth<sup>10+</sup>   | number | 是   | 图片实际绘制的宽度。<br/>单位:像素<br>**说明:**<br/>仅在loadingStatus返回1时有效。 |
576| contentHeight<sup>10+</sup>  | number | 是   | 图片实际绘制的高度。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
577| contentOffsetX<sup>10+</sup> | number | 是   | 实际绘制内容相对于组件自身的x轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
578| contentOffsetY<sup>10+</sup> | number | 是   | 实际绘制内容相对于组件自身的y轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
579
580### onError<sup>9+</sup>
581
582onError(callback: ImageErrorCallback)
583
584图片加载异常时触发该回调。
585
586当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
587
588**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
589
590**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
591
592**系统能力:** SystemCapability.ArkUI.ArkUI.Full
593
594**参数:**
595
596| 参数名   | 类型                                       | 必填 | 说明                       |
597| -------- | ------------------------------------------ | ---- | -------------------------- |
598| callback | [ImageErrorCallback](#imageerrorcallback9) | 是   | 图片加载异常时触发的回调。<br>**说明:**<br/> - 建议开发者使用此回调,可快速确认图片加载失败时的具体原因 |
599
600### onFinish
601
602onFinish(event: () =&gt; void)
603
604当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。
605
606仅支持svg格式的图片。当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
607
608**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
609
610**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
611
612**系统能力:** SystemCapability.ArkUI.ArkUI.Full
613
614## ImageErrorCallback<sup>9+</sup>
615
616type ImageErrorCallback = (error: ImageError) => void
617
618图片加载异常时触发的回调。
619
620当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
621
622**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
623
624**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
625
626**系统能力:** SystemCapability.ArkUI.ArkUI.Full
627
628| 参数名 | 类型                       | 必填 | 说明                               |
629| ------ | -------------------------- | ---- | ---------------------------------- |
630| error  | [ImageError](#imageerror9) | 是   | 图片加载异常时触发回调的返回对象。 |
631
632## ImageError<sup>9+</sup>
633
634图片加载异常时触发回调的返回对象。
635
636当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
637
638**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
639
640**系统能力:** SystemCapability.ArkUI.ArkUI.Full
641
642| 名称          | 类型   | 必填 | 说明                      |
643| --------------- | ------ | ---- | ------------------------- |
644| componentWidth  | number | 是   | 组件的宽。<br/>单位:像素<br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。 |
645| componentHeight | number | 是   | 组件的高。<br/>单位:像素<br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。 |
646| message<sup>10+</sup>         | string | 是   | 报错信息。<br/>**卡片能力:** 从API version 10开始,该接口支持在ArkTS卡片中使用。 |
647
648## 示例
649
650### 示例1(加载基本类型图片)
651
652加载png、gif、svg和jpg等基本类型的图片。
653
654```ts
655@Entry
656@Component
657struct ImageExample1 {
658  build() {
659    Column() {
660      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
661        Row() {
662          // 加载png格式图片
663          Image($r('app.media.ic_camera_master_ai_leaf'))
664            .width(110).height(110).margin(15)
665            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
666          // 加载gif格式图片
667          Image($r('app.media.loading'))
668            .width(110).height(110).margin(15)
669            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
670        }
671        Row() {
672          // 加载svg格式图片
673          Image($r('app.media.ic_camera_master_ai_clouded'))
674            .width(110).height(110).margin(15)
675            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
676          // 加载jpg格式图片
677          Image($r('app.media.ic_public_favor_filled'))
678            .width(110).height(110).margin(15)
679            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
680        }
681      }
682    }.height(320).width(360).padding({ right: 10, top: 10 })
683  }
684}
685```
686
687![zh-cn_image_0000001592882500](figures/zh-cn_image_0000001592882500.gif)
688
689### 示例2(下载与显示网络图片)
690
691加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。使用[HTTP](../../../network/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../../media/image/image-overview.md)。
692
693使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[声明权限](../../../security/AccessToken/declare-permissions.md)。
694
695```ts
696import { http } from '@kit.NetworkKit';
697import { BusinessError } from '@kit.BasicServicesKit';
698import { image } from '@kit.ImageKit';
699
700@Entry
701@Component
702struct ImageExample2 {
703  @State pixelMapImg: PixelMap | undefined = undefined;
704
705  aboutToAppear() {
706    this.requestImageUrl('https://www.example.com/xxx.png');// 请填写一个具体的网络图片地址
707  }
708
709  requestImageUrl(url: string) {
710    http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
711      if (error) {
712        console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
713      } else {
714        let imgData: ArrayBuffer = data.result as ArrayBuffer;
715        console.info(`request image success, size: ${imgData.byteLength}`);
716        let imgSource: image.ImageSource = image.createImageSource(imgData);
717        class sizeTmp {
718          height: number = 100
719          width: number = 100
720        }
721        let options: Record<string, number | boolean | sizeTmp> = {
722          'alphaType': 0,
723          'editable': false,
724          'pixelFormat': 3,
725          'scaleMode': 1,
726          'size': { height: 100, width: 100 }
727        }
728        imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
729          console.error('image createPixelMap success');
730          this.pixelMapImg = pixelMap;
731        })
732      }
733    })
734  }
735
736  build() {
737    Column() {
738      Image(this.pixelMapImg)
739        .alt($r('app.media.img'))
740        .objectFit(ImageFit.None)
741        .width('100%')
742        .height('100%')
743    }
744  }
745}
746```
747
748![zh-cn_image_0000001607845173](figures/zh-cn_image_view2.gif)
749
750### 示例3(为图片添加事件)
751
752为图片添加onClick和onFinish事件。
753
754```ts
755@Entry
756@Component
757struct ImageExample3 {
758  private imageOne: Resource = $r('app.media.earth');
759  private imageTwo: Resource = $r('app.media.star');
760  private imageThree: Resource = $r('app.media.moveStar');
761  @State src: Resource = this.imageOne
762  @State src2: Resource = this.imageThree
763  build(){
764    Column(){
765      // 为图片添加点击事件,点击完成后加载特定图片
766      Image(this.src)
767        .width(100)
768        .height(100)
769        .onClick(() => {
770          this.src = this.imageTwo
771        })
772
773      // 当加载图片为SVG格式时
774      Image(this.src2)
775        .width(100)
776        .height(100)
777        .onFinish(() => {
778          // SVG动效播放完成时加载另一张图片
779          this.src2 = this.imageOne
780        })
781    }.width('100%').height('100%')
782  }
783}
784```
785
786![zh-cn_image_0000001607845173](figures/zh-cn_image_0000001607845173.gif)
787
788### 示例4(开启图像AI分析)
789<!--RP2-->
790使用enableAnalyzer接口开启图像AI分析。
791
792```ts
793import { image } from '@kit.ImageKit'
794
795@Entry
796@Component
797struct ImageExample4 {
798  @State imagePixelMap: image.PixelMap | undefined = undefined
799  private aiController: ImageAnalyzerController = new ImageAnalyzerController()
800  private options: ImageAIOptions = {
801    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
802    aiController: this.aiController
803  }
804
805  async aboutToAppear() {
806    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
807  }
808
809  build() {
810    Column() {
811      Image(this.imagePixelMap, this.options)
812        .enableAnalyzer(true)
813        .width(200)
814        .height(200)
815        .margin({bottom:10})
816      Button('getTypes')
817        .width(80)
818        .height(80)
819        .onClick(() => {
820          this.aiController.getImageAnalyzerSupportTypes()
821        })
822    }
823  }
824  private async getPixmapFromMedia(resource: Resource) {
825    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
826      bundleName: resource.bundleName,
827      moduleName: resource.moduleName,
828      id: resource.id
829    })
830    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
831    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
832      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
833    })
834    await imageSource.release()
835    return createPixelMap
836  }
837}
838```
839
840![zh-cn_image_0000001607845173](figures/zh-cn_image_view4.gif)
841<!--RP2End-->
842### 示例5(拉伸图片)
843
844调整不同方向对图片进行拉伸。
845
846```ts
847@Entry
848@Component
849struct Index {
850  @State top: number = 40
851  @State bottom: number = 5
852  @State left: number = 40
853  @State right: number = 10
854
855  build() {
856    Column({ space: 5 }) {
857      // 原图效果
858      Image($r("app.media.sky"))
859        .width(200).height(200)
860        .border({ width: 2, color: Color.Pink })
861        .objectFit(ImageFit.Contain)
862
863      // 图像拉伸效果,设置resizable属性,对图片不同方向进行拉伸
864      Image($r("app.media.sky"))
865        .resizable({
866          slice: {
867            left: this.left,
868            right: this.right,
869            top: this.top,
870            bottom: this.bottom
871          }
872        })
873        .width(200)
874        .height(200)
875        .border({ width: 2, color: Color.Pink })
876        .objectFit(ImageFit.Contain)
877
878      Row() {
879        Button("add top to " + this.top).fontSize(10)
880          .onClick(() => {
881            this.top += 2
882          })
883        Button("add bottom to " + this.bottom).fontSize(10)
884          .onClick(() => {
885            this.bottom += 2
886          })
887      }
888
889      Row() {
890        Button("add left to " + this.left).fontSize(10)
891          .onClick(() => {
892            this.left += 2
893          })
894        Button("add right to " + this.right).fontSize(10)
895          .onClick(() => {
896            this.right += 2
897          })
898      }
899
900    }
901    .justifyContent(FlexAlign.Start).width('100%').height('100%')
902  }
903}
904```
905
906![imageResizable](figures/imageResizable.gif)
907
908### 示例6(播放PixelMap数组动画)
909
910该示例通过[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)播放PixelMap数组动画。
911
912```ts
913import {AnimationOptions, AnimatedDrawableDescriptor} from '@kit.ArkUI'
914import { image } from '@kit.ImageKit'
915
916@Entry
917@Component
918struct ImageExample {
919  pixelmaps: Array<PixelMap>  = [];
920  options: AnimationOptions = {duration:2000, iterations:1};
921  @State animated: AnimatedDrawableDescriptor | undefined = undefined;
922
923  async aboutToAppear() {
924    this.pixelmaps = await this.getPixelMaps();
925    this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
926  }
927
928  build() {
929    Column() {
930      Row() {
931        Image(this.animated)
932          .width('500px').height('500px')
933          .onFinish(() => {
934            console.info("finish")
935          })
936      }.height('50%')
937      Row() {
938        Button('once').width(100).padding(5).onClick(() => {
939          this.options = {duration:2000, iterations:1};
940          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
941        }).margin(5)
942        Button('infinite').width(100).padding(5).onClick(() => {
943          this.options = {duration:2000, iterations:-1};
944          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
945        }).margin(5)
946      }
947    }.width('50%')
948  }
949
950  private async getPixmapListFromMedia(resource: Resource) {
951    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
952      bundleName: resource.bundleName,
953      moduleName: resource.moduleName,
954      id: resource.id
955    })
956    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
957    let createPixelMap: Array<image.PixelMap> = await imageSource.createPixelMapList({
958      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
959    })
960    await imageSource.release()
961    return createPixelMap
962  }
963
964  private async getPixmapFromMedia(resource: Resource) {
965    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
966      bundleName: resource.bundleName,
967      moduleName: resource.moduleName,
968      id: resource.id
969    })
970    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
971    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
972      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
973    })
974    await imageSource.release()
975    return createPixelMap
976  }
977
978  private async getPixelMaps() {
979    let Mypixelmaps:Array<PixelMap> = await this.getPixmapListFromMedia($r('app.media.view'))//gif图, 生成多张PixelMap
980    Mypixelmaps.push(await this.getPixmapFromMedia($r('app.media.icon'))) //添加一张图片
981    return Mypixelmaps;
982  }
983}
984```
985
986![zh-cn_image_0000001607845173](figures/zh-cn_image_view6.gif)
987
988### 示例7(为图像设置颜色滤镜效果)
989
990该示例通过[colorFilter](#colorfilter9)实现了给图像设置颜色滤镜效果。
991
992```ts
993import { drawing, common2D } from '@kit.ArkGraphics2D';
994
995@Entry
996@Component
997struct ImageExample3 {
998  private imageOne: Resource = $r('app.media.1');
999  private imageTwo: Resource = $r('app.media.2');
1000  @State src: Resource = this.imageOne
1001  @State src2: Resource = this.imageTwo
1002  private ColorFilterMatrix: number[] = [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
1003  private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 };
1004  @State DrawingColorFilterFirst: ColorFilter | undefined = undefined
1005  @State DrawingColorFilterSecond: ColorFilter | undefined = undefined
1006  @State DrawingColorFilterThird: ColorFilter | undefined = undefined
1007
1008  build() {
1009    Column() {
1010      Image(this.src)
1011        .width(100)
1012        .height(100)
1013        .colorFilter(this.DrawingColorFilterFirst)
1014        .onClick(()=>{
1015          this.DrawingColorFilterFirst = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1016        })
1017
1018      Image(this.src2)
1019        .width(100)
1020        .height(100)
1021        .colorFilter(this.DrawingColorFilterSecond)
1022        .onClick(()=>{
1023          this.DrawingColorFilterSecond = new ColorFilter(this.ColorFilterMatrix);
1024        })
1025
1026      //当加载图片为SVG格式时
1027      Image($r('app.media.test_self'))
1028        .width(110).height(110).margin(15)
1029        .colorFilter(this.DrawingColorFilterThird)
1030        .onClick(()=>{
1031          this.DrawingColorFilterThird = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1032        })
1033    }
1034  }
1035}
1036```
1037![imageSetColorFilter](figures/imageSetColorFilter.gif)
1038
1039### 示例8(为图像设置填充效果)
1040
1041该示例通过[objectFit](#objectfit)为图像设置填充效果。
1042
1043```ts
1044@Entry
1045@Component
1046struct ImageExample{
1047  build() {
1048    Column() {
1049      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1050        Row() {
1051          // 加载png格式图片
1052          Image($r('app.media.sky'))
1053            .width(110).height(110).margin(15)
1054            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1055            .border({ width: 2, color: Color.Pink })
1056            .objectFit(ImageFit.TOP_START)
1057          // 加载gif格式图片
1058          Image($r('app.media.loading'))
1059            .width(110).height(110).margin(15)
1060            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1061            .border({ width: 2, color: Color.Pink })
1062            .objectFit(ImageFit.BOTTOM_START)
1063        }
1064        Row() {
1065          // 加载svg格式图片
1066          Image($r('app.media.svg'))
1067            .width(110).height(110).margin(15)
1068            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1069            .border({ width: 2, color: Color.Pink })
1070            .objectFit(ImageFit.TOP_END)
1071          // 加载jpg格式图片
1072          Image($r('app.media.jpg'))
1073            .width(110).height(110).margin(15)
1074            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1075            .border({ width: 2, color: Color.Pink })
1076            .objectFit(ImageFit.CENTER)
1077        }
1078      }
1079    }.height(320).width(360).padding({ right: 10, top: 10 })
1080  }
1081}
1082```
1083
1084![imageResizable](figures/imageSetFit.gif)
1085
1086### 示例9(切换显示不同类型图片)
1087
1088该示例展示了ResourceStr类型与ImageContent类型作为数据源的显示图片效果。
1089
1090```ts
1091@Entry
1092@Component
1093struct ImageContentExample {
1094  @State imageSrcIndex: number = 0;
1095  @State imageSrcList: (ResourceStr | ImageContent)[] = [$r('app.media.app_icon'), ImageContent.EMPTY]
1096
1097  build() {
1098    Column({ space: 10 }) {
1099      Image(this.imageSrcList[this.imageSrcIndex])
1100        .width(100)
1101        .height(100)
1102      Button('点击切换Image的src')
1103        .padding(20)
1104        .onClick(() => {
1105          this.imageSrcIndex = (this.imageSrcIndex + 1) % this.imageSrcList.length
1106        })
1107    }.width('100%')
1108    .padding(20)
1109  }
1110}
1111```
1112
1113![imageContent](figures/zh-cn_image_view9.gif)
1114
1115### 示例10(配置隐私隐藏)
1116
1117该示例通过[privacySensitive](#privacysensitive12)展示了如何配置隐私隐藏,效果展示需要卡片框架支持。
1118
1119```ts
1120@Entry
1121@Component
1122struct ImageExample {
1123  build() {
1124    Column({ space: 10 }) {
1125      Image($r("app.media.startIcon"))
1126        .width(50)
1127        .height(50)
1128        .margin({top :30})
1129        .privacySensitive(true)
1130    }
1131    .alignItems(HorizontalAlign.Center)
1132    .width("100%")
1133  }
1134}
1135```
1136
1137![imageContent](figures/zh-cn_image_view10.gif)
1138
1139### 示例11(为图片设置扫光效果)
1140
1141该示例通过[linearGradient](./ts-basic-components-datapanel.md#lineargradient10)接口和[animateTo()](./ts-explicit-animation.md)实现了给图片设置扫光效果。
1142
1143```ts
1144import { curves } from '@kit.ArkUI';
1145
1146@Entry
1147@Component
1148struct ImageExample11 {
1149  private curve = curves.cubicBezier(0.33, 0, 0.67, 1);
1150  @State moveImg: string[] = ['imageScanEffect'];
1151  @State moveImgVisible: Visibility = Visibility.Visible;
1152  @State durationTime: number = 1500;
1153  @State iterationsTimes: number = -1;
1154  @State private opacityValue: number = 0.5;
1155  @State imageWidth: number = 450;
1156  @State visible: Visibility = Visibility.Hidden;
1157  @State stackBackgroundColor: string = '#E1E4E9';
1158  @State linePositionX: number = 0 - this.imageWidth;
1159  @State linePositionY: number = 0;
1160  @State imgResource: Resource | undefined = undefined;
1161
1162  startupAnimate() {
1163    this.moveImg.pop();
1164    this.moveImg.push('imageScanEffect');
1165    setTimeout(() => {
1166      this.imgResource = $r('app.media.img');
1167    }, 3000);
1168    animateTo({
1169      duration: this.durationTime,
1170      curve: this.curve,
1171      tempo: 1,
1172      iterations: this.iterationsTimes,
1173      delay: 0
1174    }, () => {
1175      this.linePositionX = this.imageWidth;
1176    })
1177  }
1178
1179  build() {
1180    Column() {
1181      Row() {
1182        Stack() {
1183          Image(this.imgResource)
1184            .width(this.imageWidth)
1185            .height(200)
1186            .objectFit(ImageFit.Contain)
1187            .visibility(this.visible)
1188            .onComplete(() => {
1189              this.visible = Visibility.Visible;
1190              this.moveImg.pop();
1191            })
1192            .onError(() =>{
1193              setTimeout(() => {
1194                this.visible = Visibility.Visible;
1195                this.moveImg.pop();
1196              }, 2600)
1197            })
1198          ForEach(this.moveImg, (item: string) => {
1199            Row()
1200              .width(this.imageWidth)
1201              .height(200)
1202              .visibility(this.moveImgVisible)
1203              .position({ x: this.linePositionX, y: this.linePositionY })
1204              .linearGradient({
1205                direction: GradientDirection.Right,
1206                repeating: false,
1207                colors: [[0xE1E4E9, 0], [0xFFFFFF, 0.75], [0xE1E4E9, 1]]
1208              })
1209              .opacity(this.opacityValue)
1210          })
1211        }
1212        .backgroundColor(this.visible ? this.stackBackgroundColor : undefined)
1213        .margin({top: 20, left: 20, right: 20})
1214        .borderRadius(20)
1215        .clip(true)
1216        .onAppear(() => {
1217          this.startupAnimate();
1218        })
1219      }
1220    }
1221  }
1222}
1223```
1224
1225![imageContent](figures/imageScanEffect.gif)