ts-basic-components-image.md 15.3 KB
Newer Older
Z
zengyawen 已提交
1
# Image
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
The **\<Image>** component is used to render and display local and online images.
Z
zengyawen 已提交
4

E
ester.zhou 已提交
5 6
> **NOTE**
>
Z
zengyawen 已提交
7
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
8 9


Z
zengyawen 已提交
10 11
## Required Permissions

E
ester.zhou 已提交
12 13 14 15 16 17 18 19 20 21 22
To use online images, you need to add the **ohos.permission.INTERNET** permission to the corresponding abilities in the **config.json** (for the FA model) or **module.json5** file (for the stage model).

```
"abilities": [
  {
    ...
    "permissions": ["ohos.permission.INTERNET"],
    ...
  }
] 
```
Z
zengyawen 已提交
23 24 25


## Child Components
Z
zengyawen 已提交
26

E
ester.zhou 已提交
27
Not supported
Z
zengyawen 已提交
28

Z
zengyawen 已提交
29 30 31

## APIs

E
ester.zhou 已提交
32
Image(src: string | PixelMap | Resource)
Z
zengyawen 已提交
33

E
ester.zhou 已提交
34
Obtains an image from the specified source for subsequent rendering and display.
Z
zengyawen 已提交
35

E
ester.zhou 已提交
36 37
**Parameters**

E
ester.zhou 已提交
38 39 40
| Name | Type                                    | Mandatory  | Default Value | Description                                    |
| ---- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| src  | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](../../ui/ts-types.md#resource-type) | Yes   | -    | Image source. Both local and online images are supported.<br>When using resources referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** 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 following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.|
Z
zengyawen 已提交
41 42 43

## Attributes

E
ester.zhou 已提交
44 45
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.

E
ester.zhou 已提交
46 47 48 49 50 51 52
| Name                 | Type                                               | Default Value                  | Description                                                        |
| --------------------- | ------------------------------------------------------- | ------------------------ | ------------------------------------------------------------ |
| alt                   | string \| [Resource](../../ui/ts-types.md#resource-type) | -                        | Placeholder image displayed during loading. Both local and Internet URIs are supported.                |
| objectFit             | ImageFit                           | ImageFit.Cover           | Image scale type.                                        |
| objectRepeat          | [ImageRepeat](ts-appendix-enums.md#imagerepeat)         | NoRepeat                 | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| interpolation         | [ImageInterpolation](#imageinterpolation)               | ImageInterpolation.None  | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>**NOTE**<br>> This attribute is not applicable to SVG images.<br>> This attribute is not applicable to **PixelMap** objects. |
| renderMode            | [ImageRenderMode](#imagerendermode)                     | ImageRenderMode.Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
E
ester.zhou 已提交
53 54
| sourceSize            | {<br>width: number,<br>height: number<br>} | -                        | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. |
| syncLoad<sup>8+</sup> | boolean                                  | false                    | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
E
ester.zhou 已提交
55 56
| copyOption<sup>9+</sup> | [CopyOptions](#copyoptions) | CopyOptions.None | Whether the image can be copied. (SVG images cannot be copied.)|
| colorFilter<sup>9+</sup> | [ColorFilter](../../ui/ts-types.md) | - | Color filter of the image. |
E
ester.zhou 已提交
57 58 59

### ImageFit

E
ester.zhou 已提交
60 61 62 63 64 65 66
| Name     | Description                                                        |
| --------- | ------------------------------------------------------------ |
| Cover     | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.|
| Contain   | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries.  |
| Fill      | The image is scaled to fill the display area, and its aspect ratio is not retained.            |
| None      | The image is displayed in its original size.                                          |
| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size.                      |
E
ester.zhou 已提交
67 68

### ImageInterpolation
Z
zengyawen 已提交
69

E
ester.zhou 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82
| Name    | Description                       |
| ------ | ------------------------- |
| None   | Interpolation image data is not used.               |
| High   | The interpolation image data is used at the high level, which may affect the image rendering speed.|
| Medium | The interpolation image data is used at the medium level.             |
| Low    | The interpolation image data is used at the low level.             |

### ImageRenderMode

| Name      | Description                   |
| -------- | --------------------- |
| Original | The image is rendered based on the original image, including the color.       |
| Template | The image is rendered as a template image, and its color is ignored.|
Z
zengyawen 已提交
83

E
ester.zhou 已提交
84 85 86 87 88 89 90 91 92
### CopyOptions<sup>9+</sup>

| Name| Description|
| -------- | -------- |
| None | Copy and paste is not allowed.|
| InApp | Intra-application copy and paste is allowed.|
| LocalDevice | Intra-device copy and paste is allowed.|
| CrossDevice | Cross-device copy and paste is allowed.|

Z
zengyawen 已提交
93 94
## Events

E
ester.zhou 已提交
95
In addition to the universal events (ts-universal-events-click.md), the following events are supported.
Z
zengyawen 已提交
96

E
ester.zhou 已提交
97 98 99 100 101
| Name                                                         | Description                                                  |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br> |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels. |
| onFinish(callback: () =&gt; void)                            | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. |
Z
zengyawen 已提交
102 103 104

## Example

E
ester.zhou 已提交
105
### Loading Images
Z
zengyawen 已提交
106

E
ester.zhou 已提交
107 108 109
Load and display different types of images and set the scale type of the images.

```ts
Z
zengyawen 已提交
110 111 112
@Entry
@Component
struct ImageExample1 {
Z
zengyawen 已提交
113
  private on: string = 'www.example.com' 
Z
zengyawen 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  @State src: string = this.on

  build() {
    Column() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
        Text('default').fontSize(16).fontColor(0xcccccc).height(30)
        Row({ space: 5 }) {
          Image($r('app.media.ic_png'))
            .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_gif'))
            .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_svg'))
            .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
        Row({ space: 5 }) {
          Image($r('app.media.img_example'))
            .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image(this.src)
            .width(110).height(110).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .overlay('network', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }.margin({ top: 25, bottom: 10 })
      }

      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
        Text('objectFit').fontSize(16).fontColor(0xcccccc).height(30)
        Row({ space: 5 }) {
          Image($r('app.media.img_example'))
            .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .objectFit(ImageFit.None).width(110).height(110)
            .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example'))
            .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .objectFit(ImageFit.Fill).width(110).height(110)
            .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example'))
            .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .objectFit(ImageFit.Cover).width(110).height(110)
            .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
        Row({ space: 5 }) {
          Image($r('app.media.img_example_w250'))
            .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .objectFit(ImageFit.Contain).width(110).height(110)
            .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_example_w250'))
            .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
            .objectFit(ImageFit.ScaleDown).width(110).height(110)
            .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }.margin({ top: 25 })
      }
    }.height(320).width(360).padding({ right: 10, top: 10 })
  }
}
```

Z
zengyawen 已提交
173 174
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)

E
ester.zhou 已提交
175
### Setting Attributes
Z
zengyawen 已提交
176

E
ester.zhou 已提交
177
```ts
Z
zengyawen 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
@Entry
@Component
struct ImageExample2 {

  build() {
    Column({ space: 10 }) {
      Text('renderMode').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Row({ space: 50 }) {
        Image($r('app.media.img_example'))
          .renderMode(ImageRenderMode.Original).width(100).height(100)
          .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_example'))
          .renderMode(ImageRenderMode.Template).width(100).height(100)
          .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
E
ester.zhou 已提交
195
      
Z
zengyawen 已提交
196 197 198 199
      Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Image('')
        .alt($r('app.media.Image_none'))
        .width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
E
ester.zhou 已提交
200
        
Z
zengyawen 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%')
      Row({ space: 50 }) {
        Image($r('app.media.img_example'))
          .sourceSize({
            width: 150,
            height: 150
          })
          .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1)
          .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .overlay('w:150 h:150', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_example'))
          .sourceSize({
            width: 200,
            height: 200
          })
          .objectFit(ImageFit.ScaleDown).width('25%').aspectRatio(1)
          .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
E
ester.zhou 已提交
220
      
Z
zengyawen 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Row({ space: 5 }) {
        Image($r('app.media.ic_health_heart'))
          .width(120).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .objectRepeat(ImageRepeat.XY).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_health_heart'))
          .width(110).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .objectRepeat(ImageRepeat.Y).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_health_heart'))
          .width(110).height(125).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
          .objectRepeat(ImageRepeat.X).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding({ right: 10 })
  }
}
```

Z
zengyawen 已提交
241 242
![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png)

E
ester.zhou 已提交
243
### Invoking Events
Z
zengyawen 已提交
244

E
ester.zhou 已提交
245
```ts
Z
zengyawen 已提交
246 247 248
@Entry
@Component
struct ImageExample3 {
E
ester.zhou 已提交
249 250
  @State widthValue: number = 0
  @State heightValue: number = 0
E
ester.zhou 已提交
251 252 253 254
  private on: Resource = $r('app.media.image_on')
  private off: Resource = $r('app.media.image_off')
  private on2off: Resource = $r('app.media.image_on2off')
  private off2on: Resource = $r('app.media.image_off2on')
Z
zengyawen 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268
  @State src: Resource = this.on

  build() {
    Column() {
      Row({ space: 20 }) {
        Column() {
          Image($r('app.media.img_example1'))
            .alt($r('app.media.ic_public_picture'))
            .sourceSize({
              width: 900,
              height: 900
            })
            .objectFit(ImageFit.Cover)
            .height(180).width(180)
E
ester.zhou 已提交
269
            // Obtain the size of an image after the image loading is complete.
Z
zengyawen 已提交
270
            .onComplete((msg: { width: number,height: number }) => {
E
ester.zhou 已提交
271 272
              this.widthValue = msg.width
              this.heightValue = msg.height
Z
zengyawen 已提交
273 274 275 276 277 278 279 280 281
            })
            .onError(() => {
              console.log('load image fail')
            })
            .overlay('\nwidth: ' + String(this.width) + ' height: ' + String(this.height), {
              align: Alignment.Bottom,
              offset: { x: 0, y: 20 }
            })
        }
E
ester.zhou 已提交
282
        // Add a click event so that a specific image is loaded upon clicking.
Z
zengyawen 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        Image(this.src)
          .width(120).height(120)
          .onClick(() => {
            if (this.src == this.on || this.src == this.off2on) {
              this.src = this.on2off
            } else {
              this.src = this.off2on
            }
          })
          .onFinish(() => {
            if (this.src == this.off2on) {
              this.src = this.on
            } else {
              this.src = this.off
            }
          })
      }
    }.width('100%')
  }
}
```

Z
zengyawen 已提交
305
![en-us_image_0000001256858397](figures/en-us_image_0000001256858397.gif)