• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ImageSpan
2
3As a child of the [Text](ts-basic-components-text.md) and [ContainerSpan](ts-basic-components-containerspan.md) components, the **ImageSpan** component is used to display inline images.
4
5>  **NOTE**
6>
7>  This component is supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12Not supported
13
14
15## APIs
16
17ImageSpan(value: ResourceStr | PixelMap)
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name| Type| Mandatory| Description|
26| -------- | -------- | -------- | -------- |
27| value | [ResourceStr](ts-types.md#resourcestr) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)  | Yes| Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, **ImageSpan("common/test.jpg")**, the **ImageSpan** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.<br>\- The supported formats include PNG, JPG, BMP, SVG, GIF, and HEIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.<br>\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.|
28
29
30## Attributes
31
32The attributes inherit from [BaseSpan](ts-basic-components-span.md#basespan). Among the universal attributes, [size](ts-universal-attributes-size.md#size), [background](ts-universal-attributes-background.md#background), and [border](ts-universal-attributes-border.md#border) are supported.
33
34### alt<sup>12+</sup>
35
36alt(value: PixelMap)
37
38Sets the placeholder image displayed during loading.
39
40**Atomic service API**: This API can be used in atomic services since API version 12.
41
42**System capability**: SystemCapability.ArkUI.ArkUI.Full
43
44**Parameters**
45
46| Name| Type                                                    | Mandatory| Description                                                        |
47| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
48| value  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes  | Placeholder image displayed during loading. The [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type is supported.<br>Default value: **null**|
49
50### verticalAlign
51
52verticalAlign(value: ImageSpanAlignment)
53
54Sets the alignment mode of the image relative to the line height.
55
56**Atomic service API**: This API can be used in atomic services since API version 11.
57
58**System capability**: SystemCapability.ArkUI.ArkUI.Full
59
60**Parameters**
61
62| Name| Type                                     | Mandatory| Description                                                        |
63| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
64| value  | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) | Yes  | Alignment mode of the image relative to the line height.<br>Default value: **ImageSpanAlignment.BOTTOM**|
65
66### objectFit
67
68objectFit(value: ImageFit)
69
70Sets the image scale type.
71
72**Atomic service API**: This API can be used in atomic services since API version 11.
73
74**System capability**: SystemCapability.ArkUI.ArkUI.Full
75
76**Parameters**
77
78| Name| Type                                     | Mandatory| Description                                       |
79| ------ | ----------------------------------------- | ---- | ------------------------------------------- |
80| value  | [ImageFit](ts-appendix-enums.md#imagefit) | Yes  | Image scale type.<br>Default value: **ImageFit.Cover**|
81
82## Events
83
84Among all the universal events, only the [click event](ts-universal-attributes-click.md) is supported. The following events are also supported.
85
86### onComplete<sup>12+</sup>
87
88onComplete(callback: ImageCompleteCallback)
89
90Triggered when the image is successfully loaded or decoded. The size of the loaded image is returned.
91
92**Atomic service API**: This API can be used in atomic services since API version 12.
93
94**System capability**: SystemCapability.ArkUI.ArkUI.Full
95
96**Parameters**
97
98| Name  | Type                                      | Mandatory| Description                      |
99| -------- | ------------------------------------------ | ---- | -------------------------- |
100| callback | [ImageCompleteCallback](#imagecompletecallback12) | Yes  | Callback triggered when the image is successfully loaded or decoded.|
101
102### onError<sup>12+</sup>
103
104onError(callback: ImageErrorCallback)
105
106Triggered when an error occurs during image loading.
107
108**Atomic service API**: This API can be used in atomic services since API version 12.
109
110**System capability**: SystemCapability.ArkUI.ArkUI.Full
111
112**Parameters**
113
114| Name  | Type                                      | Mandatory| Description                      |
115| -------- | ------------------------------------------ | ---- | -------------------------- |
116| callback | [ImageErrorCallback](ts-basic-components-image.md#imageerrorcallback9) | Yes  | Callback triggered when an error occurs during image loading.|
117
118## ImageCompleteCallback<sup>12+</sup>
119
120type ImageCompleteCallback = (result: ImageLoadResult) => void
121
122Triggered when the image is successfully loaded.
123
124**Atomic service API**: This API can be used in atomic services since API version 12.
125
126**System capability**: SystemCapability.ArkUI.ArkUI.Full
127
128| Name| Type                      | Mandatory| Description                              |
129| ------ | -------------------------- | ---- | ---------------------------------- |
130| result  | [ImageLoadResult](#imageloadresult12) | Yes  | Object returned after the callback is triggered when an image is successfully loaded or decoded.|
131
132## ImageLoadResult<sup>12+</sup>
133
134Object returned after the callback is triggered when an image is successfully loaded or decoded.
135
136**Atomic service API**: This API can be used in atomic services since API version 12.
137
138**System capability**: SystemCapability.ArkUI.ArkUI.Full
139
140| Name                      | Type  | Mandatory| Description                                                        |
141| ---------------------------- | ------ | ---- | ------------------------------------------------------------ |
142| width                        | number | Yes  | Width of the image.<br>Unit: pixel                                   |
143| height                       | number | Yes  | Height of the image.<br>Unit: pixel                                   |
144| componentWidth               | number | Yes  | Width of the component.<br>Unit: pixel                                   |
145| componentHeight              | number | Yes  | Height of the component.<br>Unit: pixel                                   |
146| loadingStatus                | number | Yes  | Loading status of the image.<br>**NOTE**<br>If the return value is **0**, the image is successfully loaded. If the return value is **1**, the image is successfully decoded.|
147| contentWidth   | number | Yes  | Actual rendered width of the image.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
148| contentHeight  | number | Yes  | Actual rendered height of the image.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
149| contentOffsetX | number | Yes  | Offset of the rendered content relative to the component on the x-axis.<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
150| contentOffsetY | number | Yes  | Offset of the rendered content relative to the component on the y-axis<br>Unit: pixel<br>**NOTE**<br>This parameter is valid only when the return value of **loadingStatus** is **1**.|
151
152
153
154## Example
155
156### Example 1
157
158This example sets the basic attributes of the image span as well as the alignment mode of the image with the text.
159
160```ts
161// xxx.ets
162@Entry
163@Component
164struct SpanExample {
165  build() {
166    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
167      Text() {
168        Span('This is the Span and ImageSpan component').fontSize(25).textCase(TextCase.Normal)
169          .decoration({ type: TextDecorationType.None, color: Color.Pink })
170      }.width('100%').textAlign(TextAlign.Center)
171
172      Text() {
173        ImageSpan($r('app.media.icon'))
174          .width('200px')
175          .height('200px')
176          .objectFit(ImageFit.Fill)
177          .verticalAlign(ImageSpanAlignment.CENTER)
178        Span('I am LineThrough-span')
179          .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }).fontSize(25)
180        ImageSpan($r('app.media.icon'))
181          .width('50px')
182          .height('50px')
183          .verticalAlign(ImageSpanAlignment.TOP)
184        Span('I am Underline-span')
185          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25)
186        ImageSpan($r('app.media.icon'))
187          .size({ width: '100px', height: '100px' })
188          .verticalAlign(ImageSpanAlignment.BASELINE)
189        Span('I am Underline-span')
190          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25)
191        ImageSpan($r('app.media.icon'))
192          .width('70px')
193          .height('70px')
194          .verticalAlign(ImageSpanAlignment.BOTTOM)
195        Span('I am Underline-span')
196          .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(50)
197      }
198      .width('100%')
199      .textIndent(50)
200    }.width('100%').height('100%').padding({ left: 0, right: 0, top: 0 })
201  }
202}
203```
204
205![imagespan](figures/imagespan.png)
206
207### Example 2
208
209This example shows how to set the background style of an image span.
210
211```ts
212// xxx.ets
213@Component
214@Entry
215struct Index {
216  build() {
217    Column() {
218      Text() {
219        ImageSpan($r('app.media.app_icon'))
220          .width('60vp')
221          .height('60vp')
222          .verticalAlign(ImageSpanAlignment.CENTER)
223          .textBackgroundStyle({color: Color.Green, radius: "5vp"})
224      }
225    }.width('100%').alignItems(HorizontalAlign.Center)
226  }
227}
228```
229![imagespan](figures/image_span_textbackgroundstyle.png)
230
231### Example 3
232This example implements a callback triggered when the image is successfully loaded or decoded and a callback triggered when an error occurs during image loading.
233```ts
234// xxx.ets
235@Entry
236@Component
237struct Index {
238  @State src: ResourceStr = $r('app.media.icon');
239  build(){
240    Column(){
241      Text(){
242        ImageSpan(this.src)
243          .width(100).height(100)
244          .onError((err)=>{
245            console.log("onError:" + err.message)
246          })
247          .onComplete((event)=>{
248            console.log("onComplete: " + event.loadingStatus)
249          })
250      }
251    }.width('100%').height('100%')
252  }
253}
254```
255
256### Example 4
257
258This example shows how a placeholder image is used in **ImageSpan** during the process of loading an image from the Internet.
259
260```ts
261// xxx.ets
262import { http } from '@kit.NetworkKit'
263import { image } from '@kit.ImageKit'
264import { BusinessError } from '@kit.BasicServicesKit'
265
266@Entry
267@Component
268struct SpanExample {
269  @State imageAlt: PixelMap | undefined = undefined
270
271  httpRequest() {
272    // Enter an image URL.
273    http.createHttp().request("https://www.example.com/xxx.png", (error: BusinessError, data: http.HttpResponse) => {
274      if (error) {
275        console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`)
276      } else {
277        console.log(`http request success.`)
278        let imageData: ArrayBuffer = data.result as ArrayBuffer
279        let imageSource: image.ImageSource = image.createImageSource(imageData)
280
281        class tmp {
282          height: number = 100
283          width: number = 100
284        }
285
286        let option: Record<string, number | boolean | tmp> = {
287          'alphaType': 0, // Alpha type.
288          'editable': false, // Whether the image is editable.
289          'pixelFormat': 3, // Pixel format.
290          'scaleMode': 1, // Scale mode.
291          'size': { height: 100, width: 100 }
292        }
293        // Image size.
294        imageSource.createPixelMap(option).then((pixelMap: PixelMap) => {
295          this.imageAlt = pixelMap
296        })
297      }
298    })
299  }
300
301  build() {
302    Column() {
303      Button("Get Online Image")
304        .onClick(() => {
305          this.httpRequest()
306        })
307
308      Text() {
309        // Enter an image URL.
310        ImageSpan('https://www.example.com/xxx.png')
311          .alt(this.imageAlt)
312          .width(300)
313          .height(300)
314      }
315
316    }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 })
317  }
318}
319```
320
321![imagespan](figures/image_span_alt.gif)
322