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: ImageSourceSize)
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  | [ImageSourceSize](#imagesourcesize14对象说明) | 是   | 图片解码尺寸参数,降低图片的分辨率,常用于需要让图片显示尺寸比组件尺寸更小的场景。和ImageFit.None配合使用时可在组件内显示小图。 |
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**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
393
394**系统能力:** SystemCapability.ArkUI.ArkUI.Full
395
396**参数:**
397
398| 参数名 | 类型    | 必填 | 说明                                                         |
399| ------ | ------- | ---- | ------------------------------------------------------------ |
400| enable  | boolean | 是   | 组件支持AI分析,设置为true时,组件可进行AI分析。<br/>默认值:false |
401
402### resizable<sup>11+</sup>
403
404resizable(value: ResizableOptions)
405
406设置图像拉伸时可调整大小的图像选项。拉伸对拖拽缩略图以及占位图有效。
407
408设置合法的 [ResizableOptions](#resizableoptions11) 时,objectRepeat 属性设置不生效。
409
410当设置 top +bottom 大于原图的高或者 left + right 大于原图的宽时 [ResizableOptions](#resizableoptions11) 属性设置不生效。
411
412当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时设置该属性不生效。
413
414**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
415
416**系统能力:** SystemCapability.ArkUI.ArkUI.Full
417
418**参数:**
419
420| 参数名 | 类型                                    | 必填 | 说明                             |
421| ------ | --------------------------------------- | ---- | -------------------------------- |
422| value  | [ResizableOptions](#resizableoptions11) | 是   | 图像拉伸时可调整大小的图像选项。 |
423
424### privacySensitive<sup>12+</sup>
425
426privacySensitive(supported: boolean)
427
428设置是否支持卡片敏感隐私信息。
429
430**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
431
432**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
433
434**系统能力:** SystemCapability.ArkUI.ArkUI.Full
435
436**参数:**
437
438| 参数名    | 类型    | 必填 | 说明                     |
439| --------- | ------- | ---- | ------------------------ |
440| supported | boolean | 是   | 是否支持卡片敏感隐私信息。<br/>默认值为false,当设置为true时,隐私模式下图片将显示为半透明底板样式。<br/>**说明:** <br/>设置null则不敏感。<br/>进入隐私模式需要[卡片框架支持](./ts-universal-attributes-obscured.md)。 |
441
442### dynamicRangeMode<sup>12+</sup>
443
444dynamicRangeMode(value: DynamicRangeMode)
445
446设置期望展示的图像动态范围。
447
448<!--RP1--><!--RP1End-->
449
450**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
451
452**系统能力:** SystemCapability.ArkUI.ArkUI.Full
453
454**参数:**
455
456| 参数名 | 类型                                    | 必填 | 说明                             |
457| ------ | --------------------------------------- | ---- | -------------------------------- |
458| value  | [DynamicRangeMode](#dynamicrangemode12-1) | 是   | 图像显示的动态范围。<br/>默认值:dynamicRangeMode.Standard |
459
460## ImageContent<sup>12+</sup>
461
462指定图像内容。
463
464**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
465
466**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
467
468**系统能力:** SystemCapability.ArkUI.ArkUI.Full
469
470| 名称     | 说明                    |
471| ------ | -------------------------- |
472| EMPTY   | 空图像。                   |
473
474## ImageInterpolation
475
476**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
477
478**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
479
480**系统能力:** SystemCapability.ArkUI.ArkUI.Full
481
482| 名称     | 说明                       |
483| ------ | -------------------------- |
484| None   | 最近邻插值。                   |
485| High   | Cubic插值,插值质量最高,可能会影响图片渲染的速度。 |
486| Medium | MipMap插值。                     |
487| Low    | 双线性插值。                     |
488
489## ImageRenderMode
490
491**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
492
493**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
494
495**系统能力:** SystemCapability.ArkUI.ArkUI.Full
496
497| 名称     | 说明           |
498| -------- | -------------- |
499| Original | 原色渲染模式。 |
500| Template | 黑白渲染模式。 |
501
502## ResizableOptions<sup>11+</sup>
503
504图像拉伸时可调整大小的图像选项。
505
506**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
507
508**系统能力:** SystemCapability.ArkUI.ArkUI.Full
509
510| 名称 | 类型 | 必填 | 说明 |
511| --------- |-----------|-----------|-----------|
512| slice | [EdgeWidths](#edgewidths参数说明) |  否  | 边框宽度类型,用于描述组件边框不同方向的宽度。<br>**说明:**<br>只有当bottom和right同时大于0时,该属性生效。 |
513| 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)接口不生效。 |
514
515## EdgeWidths参数说明
516
517**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
518
519**系统能力:** SystemCapability.ArkUI.ArkUI.Full
520
521| 名称 | 类型 | 必填 | 说明 |
522| --------- |-----------|-----------|-----------|
523|  top    |  [Length](ts-types.md#length)  |  否  | 图片顶部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
524|  right  |  [Length](ts-types.md#length)  |  否  | 图片右部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
525|  bottom |  [Length](ts-types.md#length)  |  否  | 图片底部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
526|  left   |  [Length](ts-types.md#length)  |  否  | 图片左部拉伸时保持不变距离。<br>默认值:0<br>单位:vp |
527
528![edgewidths](figures/edgewidths.png)
529
530## DynamicRangeMode<sup>12+</sup>
531
532期望展示的图像动态范围。
533
534**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
535
536**系统能力:** SystemCapability.ArkUI.ArkUI.Full
537
538| 名称     | 值    | 说明                    |
539| ------ | -------------------------- | -------------------------- |
540| HIGH   | 0  | 不受限动态范围,最大限度进行图片提亮。              |
541| CONSTRAINT | 1 | 受限动态范围,受限进行图片提亮。          |
542| STANDARD | 2 | 标准动态范围,不进行图片提亮。         |
543
544## ImageSourceSize<sup>14+</sup>对象说明
545
546**卡片能力:** 从API version 14开始,该接口支持在ArkTS卡片中使用。
547
548**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
549
550**系统能力:** SystemCapability.ArkUI.ArkUI.Full
551
552| 参数名 | 类型       | 必填 | 说明           |
553| ------ | --------- | ---- | ------------- |
554| width  | number | 是   | 图片解码尺寸宽度。<br/>单位:vp |
555| height  | number | 是   | 图片解码尺寸高度。<br/>单位:vp |
556
557## 事件
558
559除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
560
561### onComplete
562
563onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number }) =&gt; void)
564
565图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。
566
567当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
568
569**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
570
571**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
572
573**系统能力:** SystemCapability.ArkUI.ArkUI.Full
574
575**参数:**
576
577| 参数名                       | 类型   | 必填 | 说明                                                         |
578| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
579| width                        | number | 是   | 图片的宽。<br/>单位:像素                                    |
580| height                       | number | 是   | 图片的高。<br/>单位:像素                                    |
581| componentWidth               | number | 是   | 组件的宽。<br/>单位:像素                                    |
582| componentHeight              | number | 是   | 组件的高。<br/>单位:像素                                    |
583| loadingStatus                | number | 是   | 图片加载成功的状态值。<br/>**说明:**<br/>返回的状态值为0时,表示图片数据加载成功。返回的状态值为1时,表示图片解码成功。 |
584| contentWidth<sup>10+</sup>   | number | 是   | 图片实际绘制的宽度。<br/>单位:像素<br>**说明:**<br/>仅在loadingStatus返回1时有效。 |
585| contentHeight<sup>10+</sup>  | number | 是   | 图片实际绘制的高度。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
586| contentOffsetX<sup>10+</sup> | number | 是   | 实际绘制内容相对于组件自身的x轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
587| contentOffsetY<sup>10+</sup> | number | 是   | 实际绘制内容相对于组件自身的y轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
588
589### onError<sup>9+</sup>
590
591onError(callback: ImageErrorCallback)
592
593图片加载异常时触发该回调。
594
595当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
596
597**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
598
599**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
600
601**系统能力:** SystemCapability.ArkUI.ArkUI.Full
602
603**参数:**
604
605| 参数名   | 类型                                       | 必填 | 说明                       |
606| -------- | ------------------------------------------ | ---- | -------------------------- |
607| callback | [ImageErrorCallback](#imageerrorcallback9) | 是   | 图片加载异常时触发的回调。<br>**说明:**<br/> - 建议开发者使用此回调,可快速确认图片加载失败时的具体原因 |
608
609### onFinish
610
611onFinish(event: () =&gt; void)
612
613当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。
614
615仅支持svg格式的图片。当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
616
617**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
618
619**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
620
621**系统能力:** SystemCapability.ArkUI.ArkUI.Full
622
623## ImageErrorCallback<sup>9+</sup>
624
625type ImageErrorCallback = (error: ImageError) => void
626
627图片加载异常时触发的回调。
628
629当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
630
631**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
632
633**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
634
635**系统能力:** SystemCapability.ArkUI.ArkUI.Full
636
637| 参数名 | 类型                       | 必填 | 说明                               |
638| ------ | -------------------------- | ---- | ---------------------------------- |
639| error  | [ImageError](#imageerror9) | 是   | 图片加载异常时触发回调的返回对象。 |
640
641## ImageError<sup>9+</sup>
642
643图片加载异常时触发回调的返回对象。
644
645当组件的参数类型为[AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12)时该事件不触发。
646
647**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
648
649**系统能力:** SystemCapability.ArkUI.ArkUI.Full
650
651| 名称          | 类型   | 必填 | 说明                      |
652| --------------- | ------ | ---- | ------------------------- |
653| componentWidth  | number | 是   | 组件的宽。<br/>单位:像素<br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。 |
654| componentHeight | number | 是   | 组件的高。<br/>单位:像素<br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。 |
655| message<sup>10+</sup>         | string | 是   | 报错信息。<br/>**卡片能力:** 从API version 10开始,该接口支持在ArkTS卡片中使用。 |
656
657## 示例
658
659### 示例1
660
661加载基本类型图片
662
663```ts
664@Entry
665@Component
666struct ImageExample1 {
667  build() {
668    Column() {
669      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
670        Row() {
671          // 加载png格式图片
672          Image($r('app.media.ic_camera_master_ai_leaf'))
673            .width(110).height(110).margin(15)
674            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
675          // 加载gif格式图片
676          Image($r('app.media.loading'))
677            .width(110).height(110).margin(15)
678            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
679        }
680        Row() {
681          // 加载svg格式图片
682          Image($r('app.media.ic_camera_master_ai_clouded'))
683            .width(110).height(110).margin(15)
684            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
685          // 加载jpg格式图片
686          Image($r('app.media.ic_public_favor_filled'))
687            .width(110).height(110).margin(15)
688            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
689        }
690      }
691    }.height(320).width(360).padding({ right: 10, top: 10 })
692  }
693}
694```
695
696![zh-cn_image_0000001592882500](figures/zh-cn_image_0000001592882500.gif)
697
698### 示例2
699
700加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。使用[HTTP](../../../network/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../../media/image/image-overview.md)。
701
702使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[声明权限](../../../security/AccessToken/declare-permissions.md)。
703
704```ts
705import { http } from '@kit.NetworkKit';
706import { BusinessError } from '@kit.BasicServicesKit';
707import { image } from '@kit.ImageKit';
708
709@Entry
710@Component
711struct ImageExample2 {
712  @State pixelMapImg: PixelMap | undefined = undefined;
713
714  aboutToAppear() {
715    this.requestImageUrl('https://www.example.com/xxx.png');// 请填写一个具体的网络图片地址
716  }
717
718  requestImageUrl(url: string) {
719    http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
720      if (error) {
721        console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
722      } else {
723        let imgData: ArrayBuffer = data.result as ArrayBuffer;
724        console.info(`request image success, size: ${imgData.byteLength}`);
725        let imgSource: image.ImageSource = image.createImageSource(imgData);
726        class sizeTmp {
727          height: number = 100
728          width: number = 100
729        }
730        let options: Record<string, number | boolean | sizeTmp> = {
731          'alphaType': 0,
732          'editable': false,
733          'pixelFormat': 3,
734          'scaleMode': 1,
735          'size': { height: 100, width: 100 }
736        }
737        imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
738          console.error('image createPixelMap success');
739          this.pixelMapImg = pixelMap;
740        })
741      }
742    })
743  }
744
745  build() {
746    Column() {
747      Image(this.pixelMapImg)
748        .alt($r('app.media.img'))
749        .objectFit(ImageFit.None)
750        .width('100%')
751        .height('100%')
752    }
753  }
754}
755```
756
757![zh-cn_image_0000001607845173](figures/zh-cn_image_view2.gif)
758
759### 示例3
760
761为图片添加事件
762
763```ts
764@Entry
765@Component
766struct ImageExample3 {
767  private imageOne: Resource = $r('app.media.earth');
768  private imageTwo: Resource = $r('app.media.star');
769  private imageThree: Resource = $r('app.media.moveStar');
770  @State src: Resource = this.imageOne
771  @State src2: Resource = this.imageThree
772  build(){
773    Column(){
774      // 为图片添加点击事件,点击完成后加载特定图片
775      Image(this.src)
776        .width(100)
777        .height(100)
778        .onClick(() => {
779          this.src = this.imageTwo
780        })
781
782      // 当加载图片为SVG格式时
783      Image(this.src2)
784        .width(100)
785        .height(100)
786        .onFinish(() => {
787          // SVG动效播放完成时加载另一张图片
788          this.src2 = this.imageOne
789        })
790    }.width('100%').height('100%')
791  }
792}
793```
794
795![zh-cn_image_0000001607845173](figures/zh-cn_image_0000001607845173.gif)
796
797### 示例4
798<!--RP2-->
799使用enableAnalyzer接口开启图像AI分析
800
801```ts
802import { image } from '@kit.ImageKit'
803
804@Entry
805@Component
806struct ImageExample4 {
807  @State imagePixelMap: image.PixelMap | undefined = undefined
808  private aiController: ImageAnalyzerController = new ImageAnalyzerController()
809  private options: ImageAIOptions = {
810    types: [ImageAnalyzerType.SUBJECT, ImageAnalyzerType.TEXT],
811    aiController: this.aiController
812  }
813
814  async aboutToAppear() {
815    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
816  }
817
818  build() {
819    Column() {
820      Image(this.imagePixelMap, this.options)
821        .enableAnalyzer(true)
822        .width(200)
823        .height(200)
824        .margin({bottom:10})
825      Button('getTypes')
826        .width(80)
827        .height(80)
828        .onClick(() => {
829          this.aiController.getImageAnalyzerSupportTypes()
830        })
831    }
832  }
833  private async getPixmapFromMedia(resource: Resource) {
834    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
835      bundleName: resource.bundleName,
836      moduleName: resource.moduleName,
837      id: resource.id
838    })
839    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
840    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
841      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
842    })
843    await imageSource.release()
844    return createPixelMap
845  }
846}
847```
848
849![zh-cn_image_0000001607845173](figures/zh-cn_image_view4.gif)
850<!--RP2End-->
851### 示例5
852
853调整不同方向对图片进行拉伸
854
855```ts
856@Entry
857@Component
858struct Index {
859  @State top: number = 40
860  @State bottom: number = 5
861  @State left: number = 40
862  @State right: number = 10
863
864  build() {
865    Column({ space: 5 }) {
866      // 原图效果
867      Image($r("app.media.sky"))
868        .width(200).height(200)
869        .border({ width: 2, color: Color.Pink })
870        .objectFit(ImageFit.Contain)
871
872      // 图像拉伸效果,设置resizable属性,对图片不同方向进行拉伸
873      Image($r("app.media.sky"))
874        .resizable({
875          slice: {
876            left: this.left,
877            right: this.right,
878            top: this.top,
879            bottom: this.bottom
880          }
881        })
882        .width(200)
883        .height(200)
884        .border({ width: 2, color: Color.Pink })
885        .objectFit(ImageFit.Contain)
886
887      Row() {
888        Button("add top to " + this.top).fontSize(10)
889          .onClick(() => {
890            this.top += 2
891          })
892        Button("add bottom to " + this.bottom).fontSize(10)
893          .onClick(() => {
894            this.bottom += 2
895          })
896      }
897
898      Row() {
899        Button("add left to " + this.left).fontSize(10)
900          .onClick(() => {
901            this.left += 2
902          })
903        Button("add right to " + this.right).fontSize(10)
904          .onClick(() => {
905            this.right += 2
906          })
907      }
908
909    }
910    .justifyContent(FlexAlign.Start).width('100%').height('100%')
911  }
912}
913```
914
915![imageResizable](figures/imageResizable.gif)
916
917### 示例6
918
919播放PixelMap数组动画
920
921```ts
922import {AnimationOptions, AnimatedDrawableDescriptor} from '@kit.ArkUI'
923import { image } from '@kit.ImageKit'
924
925@Entry
926@Component
927struct ImageExample {
928  pixelmaps: Array<PixelMap>  = [];
929  options: AnimationOptions = {duration:2000, iterations:1};
930  @State animated: AnimatedDrawableDescriptor | undefined = undefined;
931
932  async aboutToAppear() {
933    this.pixelmaps = await this.getPixelMaps();
934    this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
935  }
936
937  build() {
938    Column() {
939      Row() {
940        Image(this.animated)
941          .width('500px').height('500px')
942          .onFinish(() => {
943            console.info("finish")
944          })
945      }.height('50%')
946      Row() {
947        Button('once').width(100).padding(5).onClick(() => {
948          this.options = {duration:2000, iterations:1};
949          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
950        }).margin(5)
951        Button('infinite').width(100).padding(5).onClick(() => {
952          this.options = {duration:2000, iterations:-1};
953          this.animated = new AnimatedDrawableDescriptor(this.pixelmaps, this.options);
954        }).margin(5)
955      }
956    }.width('50%')
957  }
958
959  private async getPixmapListFromMedia(resource: Resource) {
960    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
961      bundleName: resource.bundleName,
962      moduleName: resource.moduleName,
963      id: resource.id
964    })
965    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
966    let createPixelMap: Array<image.PixelMap> = await imageSource.createPixelMapList({
967      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
968    })
969    await imageSource.release()
970    return createPixelMap
971  }
972
973  private async getPixmapFromMedia(resource: Resource) {
974    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
975      bundleName: resource.bundleName,
976      moduleName: resource.moduleName,
977      id: resource.id
978    })
979    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
980    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
981      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
982    })
983    await imageSource.release()
984    return createPixelMap
985  }
986
987  private async getPixelMaps() {
988    let Mypixelmaps:Array<PixelMap> = await this.getPixmapListFromMedia($r('app.media.view'))//gif图, 生成多张PixelMap
989    Mypixelmaps.push(await this.getPixmapFromMedia($r('app.media.icon'))) //添加一张图片
990    return Mypixelmaps;
991  }
992}
993```
994
995![zh-cn_image_0000001607845173](figures/zh-cn_image_view6.gif)
996
997### 示例7
998
999该示例实现了给图像设置颜色滤镜效果
1000
1001```ts
1002import { drawing, common2D } from '@kit.ArkGraphics2D';
1003
1004@Entry
1005@Component
1006struct ImageExample3 {
1007  private imageOne: Resource = $r('app.media.1');
1008  private imageTwo: Resource = $r('app.media.2');
1009  @State src: Resource = this.imageOne
1010  @State src2: Resource = this.imageTwo
1011  private ColorFilterMatrix: number[] = [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
1012  private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 };
1013  @State DrawingColorFilterFirst: ColorFilter | undefined = undefined
1014  @State DrawingColorFilterSecond: ColorFilter | undefined = undefined
1015  @State DrawingColorFilterThird: ColorFilter | undefined = undefined
1016
1017  build() {
1018    Column() {
1019      Image(this.src)
1020        .width(100)
1021        .height(100)
1022        .colorFilter(this.DrawingColorFilterFirst)
1023        .onClick(()=>{
1024          this.DrawingColorFilterFirst = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1025        })
1026
1027      Image(this.src2)
1028        .width(100)
1029        .height(100)
1030        .colorFilter(this.DrawingColorFilterSecond)
1031        .onClick(()=>{
1032          this.DrawingColorFilterSecond = new ColorFilter(this.ColorFilterMatrix);
1033        })
1034
1035      //当加载图片为SVG格式时
1036      Image($r('app.media.test_self'))
1037        .width(110).height(110).margin(15)
1038        .colorFilter(this.DrawingColorFilterThird)
1039        .onClick(()=>{
1040          this.DrawingColorFilterThird = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
1041        })
1042    }
1043  }
1044}
1045```
1046![imageSetColorFilter](figures/imageSetColorFilter.gif)
1047
1048### 示例8
1049
1050该示例实现了给图像设置objectFit效果
1051
1052```ts
1053@Entry
1054@Component
1055struct ImageExample{
1056  build() {
1057    Column() {
1058      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1059        Row() {
1060          // 加载png格式图片
1061          Image($r('app.media.sky'))
1062            .width(110).height(110).margin(15)
1063            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1064            .border({ width: 2, color: Color.Pink })
1065            .objectFit(ImageFit.TOP_START)
1066          // 加载gif格式图片
1067          Image($r('app.media.loading'))
1068            .width(110).height(110).margin(15)
1069            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1070            .border({ width: 2, color: Color.Pink })
1071            .objectFit(ImageFit.BOTTOM_START)
1072        }
1073        Row() {
1074          // 加载svg格式图片
1075          Image($r('app.media.svg'))
1076            .width(110).height(110).margin(15)
1077            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1078            .border({ width: 2, color: Color.Pink })
1079            .objectFit(ImageFit.TOP_END)
1080          // 加载jpg格式图片
1081          Image($r('app.media.jpg'))
1082            .width(110).height(110).margin(15)
1083            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
1084            .border({ width: 2, color: Color.Pink })
1085            .objectFit(ImageFit.CENTER)
1086        }
1087      }
1088    }.height(320).width(360).padding({ right: 10, top: 10 })
1089  }
1090}
1091```
1092
1093![imageResizable](figures/imageSetFit.gif)
1094
1095### 示例9
1096
1097该示例展示了ResourceStr类型与ImageContent类型作为数据源的显示图片效果。
1098
1099```ts
1100@Entry
1101@Component
1102struct ImageContentExample {
1103  @State imageSrcIndex: number = 0;
1104  @State imageSrcList: (ResourceStr | ImageContent)[] = [$r('app.media.app_icon'), ImageContent.EMPTY]
1105
1106  build() {
1107    Column({ space: 10 }) {
1108      Image(this.imageSrcList[this.imageSrcIndex])
1109        .width(100)
1110        .height(100)
1111      Button('点击切换Image的src')
1112        .padding(20)
1113        .onClick(() => {
1114          this.imageSrcIndex = (this.imageSrcIndex + 1) % this.imageSrcList.length
1115        })
1116    }.width('100%')
1117    .padding(20)
1118  }
1119}
1120```
1121
1122![imageContent](figures/zh-cn_image_view9.gif)
1123
1124### 示例10
1125
1126该示例展示了如何配置隐私隐藏,效果展示需要卡片框架支持
1127
1128```ts
1129@Entry
1130@Component
1131struct ImageExample {
1132  build() {
1133    Column({ space: 10 }) {
1134      Image($r("app.media.startIcon"))
1135        .width(50)
1136        .height(50)
1137        .margin({top :30})
1138        .privacySensitive(true)
1139    }
1140    .alignItems(HorizontalAlign.Center)
1141    .width("100%")
1142  }
1143}
1144```
1145
1146![imageContent](figures/zh-cn_image_view10.gif)
1147
1148### 示例11
1149
1150该示例实现了给图片设置扫光效果。
1151
1152```ts
1153import { curves } from '@kit.ArkUI';
1154
1155@Entry
1156@Component
1157struct ImageExample11 {
1158  private curve = curves.cubicBezier(0.33, 0, 0.67, 1);
1159  @State moveImg: string[] = ['imageScanEffect'];
1160  @State moveImgVisible: Visibility = Visibility.Visible;
1161  @State durationTime: number = 1500;
1162  @State iterationsTimes: number = -1;
1163  @State private opacityValue: number = 0.5;
1164  @State imageWidth: number = 450;
1165  @State visible: Visibility = Visibility.Hidden;
1166  @State stackBackgroundColor: string = '#E1E4E9';
1167  @State linePositionX: number = 0 - this.imageWidth;
1168  @State linePositionY: number = 0;
1169  @State imgResource: Resource | undefined = undefined;
1170
1171  startupAnimate() {
1172    this.moveImg.pop();
1173    this.moveImg.push('imageScanEffect');
1174    setTimeout(() => {
1175      this.imgResource = $r('app.media.img');
1176    }, 3000);
1177    animateTo({
1178      duration: this.durationTime,
1179      curve: this.curve,
1180      tempo: 1,
1181      iterations: this.iterationsTimes,
1182      delay: 0
1183    }, () => {
1184      this.linePositionX = this.imageWidth;
1185    })
1186  }
1187
1188  build() {
1189    Column() {
1190      Row() {
1191        Stack() {
1192          Image(this.imgResource)
1193            .width(this.imageWidth)
1194            .height(200)
1195            .objectFit(ImageFit.Contain)
1196            .visibility(this.visible)
1197            .onComplete(() => {
1198              this.visible = Visibility.Visible;
1199              this.moveImg.pop();
1200            })
1201            .onError(() =>{
1202              setTimeout(() => {
1203                this.visible = Visibility.Visible;
1204                this.moveImg.pop();
1205              }, 2600)
1206            })
1207          ForEach(this.moveImg, (item: string) => {
1208            Row()
1209              .width(this.imageWidth)
1210              .height(200)
1211              .visibility(this.moveImgVisible)
1212              .position({ x: this.linePositionX, y: this.linePositionY })
1213              .linearGradient({
1214                direction: GradientDirection.Right,
1215                repeating: false,
1216                colors: [[0xE1E4E9, 0], [0xFFFFFF, 0.75], [0xE1E4E9, 1]]
1217              })
1218              .opacity(this.opacityValue)
1219          })
1220        }
1221        .backgroundColor(this.visible ? this.stackBackgroundColor : undefined)
1222        .margin({top: 20, left: 20, right: 20})
1223        .borderRadius(20)
1224        .clip(true)
1225        .onAppear(() => {
1226          this.startupAnimate();
1227        })
1228      }
1229    }
1230  }
1231}
1232```
1233
1234![imageContent](figures/imageScanEffect.gif)