1# ImageSpan
2
3[Text](ts-basic-components-text.md)、[ContainerSpan](ts-basic-components-containerspan.md)组件的子组件,用于显示行内图片。
4
5>  **说明:**
6>
7>  该组件从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9
10## 子组件
11
1213
14
15## 接口
16
17ImageSpan(value: ResourceStr | PixelMap)
18
19**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
20
21**系统能力:** SystemCapability.ArkUI.ArkUI.Full
22
23**参数:**
24
25| 参数名 | 类型 | 必填 | 说明 |
26| -------- | -------- | -------- | -------- |
27| value | [ResourceStr](ts-types.md#resourcestr) \|&nbsp;[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)&nbsp; | 是 | 图片的数据源,支持本地图片和网络图片。<br/>当使用相对路径引用图片资源时,例如`ImageSpan("common/test.jpg")`,不支持跨包/跨模块调用该ImageSpan组件,建议使用`$r`方式来管理需全局使用的图片资源。<br/>\- 支持的图片格式包括png、jpg、bmp、svg、gif和heif。<br/>\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。<br/>\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 |
28
29
30## 属性
31
32属性继承自[BaseSpan](ts-basic-components-span.md#basespan),通用属性方法支持[尺寸设置](ts-universal-attributes-size.md#尺寸设置)、[背景设置](ts-universal-attributes-background.md#背景设置)、[边框设置](ts-universal-attributes-border.md#边框设置)
33
34### alt<sup>12+</sup>
35
36alt(value:&nbsp;PixelMap)
37
38设置图片加载时显示的占位图。
39
40**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
41
42**系统能力:** SystemCapability.ArkUI.ArkUI.Full
43
44**参数:**
45
46| 参数名 | 类型                                                     | 必填 | 说明                                                         |
47| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
48| value  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | 是   | 加载时显示的占位图,支持[PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)类型。<br/>默认值:null |
49
50### verticalAlign
51
52verticalAlign(value: ImageSpanAlignment)
53
54设置图片基于行高的对齐方式。
55
56**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
57
58**系统能力:** SystemCapability.ArkUI.ArkUI.Full
59
60**参数:**
61
62| 参数名 | 类型                                      | 必填 | 说明                                                         |
63| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
64| value  | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) | 是   | 图片基于行高的对齐方式。<br />默认值:ImageSpanAlignment.BOTTOM |
65
66### objectFit
67
68objectFit(value: ImageFit)
69
70设置图片的缩放类型。
71
72**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
73
74**系统能力:** SystemCapability.ArkUI.ArkUI.Full
75
76**参数:**
77
78| 参数名 | 类型                                      | 必填 | 说明                                        |
79| ------ | ----------------------------------------- | ---- | ------------------------------------------- |
80| value  | [ImageFit](ts-appendix-enums.md#imagefit) | 是   | 图片的缩放类型。<br/>默认值:ImageFit.Cover |
81
82### colorFilter<sup>14+</sup>
83
84colorFilter(filter: ColorFilter | DrawingColorFilter)
85
86为图像设置颜色滤镜效果。
87
88**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
89
90**系统能力:** SystemCapability.ArkUI.ArkUI.Full
91
92**参数:**
93
94| 参数名 | 类型                                    | 必填 | 说明                                                         |
95| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
96| filter  | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](ts-basic-components-image.md#drawingcolorfilter12) | 是   | 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. 支持@ohos.graphics.drawing的ColorFilter类型作为入参。<br/>**说明:** <br/>该接口中的DrawingColorfilter类型支持在原子化服务中使用。其中,svg类型的图源需具有stroke属性。|
97
98## 事件
99
100通用事件仅支持[点击事件](ts-universal-attributes-click.md)。还支持以下事件:
101
102### onComplete<sup>12+</sup>
103
104onComplete(callback: ImageCompleteCallback)
105
106图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。
107
108**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
109
110**系统能力:** SystemCapability.ArkUI.ArkUI.Full
111
112**参数:**
113
114| 参数名   | 类型                                       | 必填 | 说明                       |
115| -------- | ------------------------------------------ | ---- | -------------------------- |
116| callback | [ImageCompleteCallback](#imagecompletecallback12) | 是   | 图片数据加载成功和解码成功时触发的回调。 |
117
118### onError<sup>12+</sup>
119
120onError(callback: ImageErrorCallback)
121
122图片加载异常时触发该回调。
123
124**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
125
126**系统能力:** SystemCapability.ArkUI.ArkUI.Full
127
128**参数:**
129
130| 参数名   | 类型                                       | 必填 | 说明                       |
131| -------- | ------------------------------------------ | ---- | -------------------------- |
132| callback | [ImageErrorCallback](ts-basic-components-image.md#imageerrorcallback9) | 是   | 图片加载异常时触发的回调。 |
133
134## ImageCompleteCallback<sup>12+</sup>
135
136type ImageCompleteCallback = (result: ImageLoadResult) => void
137
138图片加载异常时触发的回调。
139
140**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
141
142**系统能力:** SystemCapability.ArkUI.ArkUI.Full
143
144| 参数名 | 类型                       | 必填 | 说明                               |
145| ------ | -------------------------- | ---- | ---------------------------------- |
146| result  | [ImageLoadResult](#imageloadresult12对象说明) | 是   | 图片数据加载成功和解码成功触发回调时返回的对象。 |
147
148## ImageLoadResult<sup>12+</sup>对象说明
149
150图片数据加载成功和解码成功触发回调时返回的对象。
151
152**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
153
154**系统能力:** SystemCapability.ArkUI.ArkUI.Full
155
156| 名称                       | 类型   | 必填 | 说明                                                         |
157| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
158| width                        | number | 是   | 图片的宽。<br/>单位:像素                                    |
159| height                       | number | 是   | 图片的高。<br/>单位:像素                                    |
160| componentWidth               | number | 是   | 组件的宽。<br/>单位:像素                                    |
161| componentHeight              | number | 是   | 组件的高。<br/>单位:像素                                    |
162| loadingStatus                | number | 是   | 图片加载成功的状态值。<br/>**说明:**<br/>返回的状态值为0时,表示图片数据加载成功。返回的状态值为1时,表示图片解码成功。 |
163| contentWidth   | number | 是   | 图片实际绘制的宽度。<br/>单位:像素<br>**说明:**<br/>仅在loadingStatus返回1时有效。 |
164| contentHeight  | number | 是   | 图片实际绘制的高度。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
165| contentOffsetX | number | 是   | 实际绘制内容相对于组件自身的x轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
166| contentOffsetY | number | 是   | 实际绘制内容相对于组件自身的y轴偏移。<br/>单位:像素<br/>**说明:**<br/>仅在loadingStatus返回1时有效。 |
167
168
169
170## 示例
171
172### 示例1(设置对齐方式)
173
174该示例通过verticalAlign、objectFit属性展示了ImageSpan的对齐方式以及缩放效果。
175
176```ts
177// xxx.ets
178@Entry
179@Component
180struct SpanExample {
181  build() {
182    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
183      Text() {
184        Span('This is the Span and ImageSpan component').fontSize(25).textCase(TextCase.Normal)
185          .decoration({ type: TextDecorationType.None, color: Color.Pink })
186      }.width('100%').textAlign(TextAlign.Center)
187
188      Text() {
189        ImageSpan($r('app.media.icon'))
190          .width('200px')
191          .height('200px')
192          .objectFit(ImageFit.Fill)
193          .verticalAlign(ImageSpanAlignment.CENTER)
194        Span('I am LineThrough-span')
195          .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }).fontSize(25)
196        ImageSpan($r('app.media.icon'))
197          .width('50px')
198          .height('50px')
199          .verticalAlign(ImageSpanAlignment.TOP)
200        Span('I am Underline-span')
201          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25)
202        ImageSpan($r('app.media.icon'))
203          .size({ width: '100px', height: '100px' })
204          .verticalAlign(ImageSpanAlignment.BASELINE)
205        Span('I am Underline-span')
206          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25)
207        ImageSpan($r('app.media.icon'))
208          .width('70px')
209          .height('70px')
210          .verticalAlign(ImageSpanAlignment.BOTTOM)
211        Span('I am Underline-span')
212          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(50)
213      }
214      .width('100%')
215      .textIndent(50)
216    }.width('100%').height('100%').padding({ left: 0, right: 0, top: 0 })
217  }
218}
219```
220
221![imagespan](figures/imagespan.png)
222
223### 示例2(设置背景样式)
224
225该示例通过textBackgroundStyle属性展示了文本设置背景样式的效果。
226
227```ts
228// xxx.ets
229@Component
230@Entry
231struct Index {
232  build() {
233    Column() {
234      Text() {
235        ImageSpan($r('app.media.app_icon'))
236          .width('60vp')
237          .height('60vp')
238          .verticalAlign(ImageSpanAlignment.CENTER)
239          .textBackgroundStyle({color: Color.Green, radius: "5vp"})
240      }
241    }.width('100%').alignItems(HorizontalAlign.Center)
242  }
243}
244```
245![imagespan](figures/image_span_textbackgroundstyle.png)
246
247### 示例3(为图片添加事件)
248
249该示例通过onComplete、onError为图片添加加载成功和加载异常的事件。
250
251```ts
252// xxx.ets
253@Entry
254@Component
255struct Index {
256  @State src: ResourceStr = $r('app.media.icon');
257  build(){
258    Column(){
259      Text(){
260        ImageSpan(this.src)
261          .width(100).height(100)
262          .onError((err)=>{
263            console.log("onError:" + err.message)
264          })
265          .onComplete((event)=>{
266            console.log("onComplete: " + event.loadingStatus)
267          })
268      }
269    }.width('100%').height('100%')
270  }
271}
272```
273### 示例4(设置颜色滤镜)
274
275该示例通过colorFilter属性展示了给ImageSpan图像设置颜色滤镜的效果。
276
277```ts
278// xxx.ets
279import { drawing, common2D } from '@kit.ArkGraphics2D';
280
281@Entry
282@Component
283struct SpanExample {
284  private ColorFilterMatrix: number[] = [0.239, 0, 0, 0, 0, 0, 0.616, 0, 0, 0, 0, 0, 0.706, 0, 0, 0, 0, 0, 1, 0];
285  @State DrawingColorFilterFirst: ColorFilter | undefined = new ColorFilter(this.ColorFilterMatrix)
286
287  build() {
288    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
289      Text() {
290        ImageSpan($r('app.media.icon'))
291          .width('50px')
292          .height('50px')
293          .colorFilter(this.DrawingColorFilterFirst)
294      }
295      .width('50%')
296      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
297        Text() {
298          ImageSpan($r('app.media.icon'))
299            .width('50px')
300            .height('50px')
301            .colorFilter(drawing.ColorFilter.createBlendModeColorFilter({ alpha: 255, red: 112, green: 112, blue: 112 }, drawing.BlendMode.SRC))
302        }
303        .width('50%')
304      }.width('100%').height('10%')
305    }.width('200%').height('100%')
306  }
307}
308```
309![imagespan](figures/image_span_colorfilter.gif)
310
311### 示例5(设置加载占位图)
312
313该示例alt属性展示了ImageSpan设置加载网络图片时占位图的效果。
314
315```ts
316// xxx.ets
317import { http } from '@kit.NetworkKit'
318import { image } from '@kit.ImageKit'
319import { BusinessError } from '@kit.BasicServicesKit'
320
321@Entry
322@Component
323struct SpanExample {
324  @State imageAlt: PixelMap | undefined = undefined
325
326  httpRequest() {
327    // 直接加载网络地址,请填写一个具体的网络图片地址
328    http.createHttp().request("https://www.example.com/xxx.png", (error: BusinessError, data: http.HttpResponse) => {
329      if (error) {
330        console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`)
331      } else {
332        console.log(`http request success.`)
333        let imageData: ArrayBuffer = data.result as ArrayBuffer
334        let imageSource: image.ImageSource = image.createImageSource(imageData)
335
336        class tmp {
337          height: number = 100
338          width: number = 100
339        }
340
341        let option: Record<string, number | boolean | tmp> = {
342          'alphaType': 0, // 透明度
343          'editable': false, // 是否可编辑
344          'pixelFormat': 3, // 像素格式
345          'scaleMode': 1, // 缩略值
346          'size': { height: 100, width: 100 }
347        }
348        //创建图片大小
349        imageSource.createPixelMap(option).then((pixelMap: PixelMap) => {
350          this.imageAlt = pixelMap
351        })
352      }
353    })
354  }
355
356  build() {
357    Column() {
358      Button("获取网络图片")
359        .onClick(() => {
360          this.httpRequest()
361        })
362
363      Text() {
364        // 直接加载网络地址,请填写一个具体的网络图片地址
365        ImageSpan('https://www.example.com/xxx.png')
366          .alt(this.imageAlt)
367          .width(300)
368          .height(300)
369      }
370
371    }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 })
372  }
373}
374```
375
376![imagespan](figures/image_span_alt.gif)
377