arkts-graphics-display.md 17.5 KB
Newer Older
E
ester.zhou 已提交
1
# Displaying Images (Image)
E
ester.zhou 已提交
2 3


E
ester.zhou 已提交
4
More often than not, you may need to display images in your application, for example, logos in buttons, online images, and local images. This is where the **\<Image>** component comes in handy. The **\<Image>** component supports a wide range of image formats, including PNG, JPG, BMP, SVG, and GIF. For details, see [Image](../reference/arkui-ts/ts-basic-components-image.md).
E
ester.zhou 已提交
5 6


E
ester.zhou 已提交
7
To use the **\<Image>** component, call the following API:
E
ester.zhou 已提交
8 9 10 11



```ts
E
ester.zhou 已提交
12
Image(src: PixelMap | ResourceStr | DrawableDescriptor)
E
ester.zhou 已提交
13 14 15
```


E
ester.zhou 已提交
16
This API obtains a local or online image from the data source specified by **src**. For details about how to load the data source, see [Loading Image Resources](#loading-image-resources).
E
ester.zhou 已提交
17 18 19 20 21 22 23


## Loading Image Resources

The **\<Image>** component supports two types of images: archived and pixel map.


E
ester.zhou 已提交
24
### Archived Type Data Sources
E
ester.zhou 已提交
25

E
ester.zhou 已提交
26
Data sources of the archived type can be classified into local resources, online resources, **Resource** objects, media library resources, and Base64 resources.
E
ester.zhou 已提交
27 28

- Local resources
E
ester.zhou 已提交
29

E
ester.zhou 已提交
30 31 32
  To load local images, create an **ets** folder and place the local images in any position in the folder.

  Then, in the **\<Image>** component, set **src** to the local image path, with the root directory being the **ets** folder.
E
ester.zhou 已提交
33 34

  ```ts
E
ester.zhou 已提交
35
  Image('images/view.jpg')
E
ester.zhou 已提交
36 37
  .width(200)
  ```
E
ester.zhou 已提交
38

E
ester.zhou 已提交
39
- Online resources
E
ester.zhou 已提交
40

E
ester.zhou 已提交
41
  To use online images, first apply for the **ohos.permission.INTERNET** permission. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). Then, in the **\<Image>** component, set **src** to the URL of the online image.
E
ester.zhou 已提交
42 43 44 45 46 47

  ```ts
  Image('https://www.example.com/example.JPG') // Replace the URL with the actual URL.
  ```

- **Resource** objects
E
ester.zhou 已提交
48

E
ester.zhou 已提交
49 50
  **Resource** objects can be used to import images across bundles and modules.

E
ester.zhou 已提交
51
  To load **Resource** objects, place images in the **resources** folder, which can be read and converted to the **Resource** objects through **$r**.
E
ester.zhou 已提交
52

E
ester.zhou 已提交
53
  **Figure 1** resources folder
E
ester.zhou 已提交
54 55 56 57 58 59 60 61 62 63 64

  ![image-resource](figures/image-resource.jpg)

  API:

  ```
  Image($r('app.media.icon'))
  ```

  You can also place the images in the **rawfile** folder.

E
ester.zhou 已提交
65
  **Figure 2** rawfile folder 
E
ester.zhou 已提交
66

E
ester.zhou 已提交
67
  ![image-rawfile](figures/image-rawfile.jpg)
E
ester.zhou 已提交
68 69 70 71 72 73 74

  API:

  ```
  Image($rawfile('snap'))
  ```

E
ester.zhou 已提交
75
- Media library **file://data/storage**
E
ester.zhou 已提交
76

E
ester.zhou 已提交
77
  To load images from the media library, use a path string that starts with **file://**.
E
ester.zhou 已提交
78 79 80 81

  1. Call the API to obtain the image URL in the media library.
      ```ts
      import picker from '@ohos.file.picker';
E
ester.zhou 已提交
82
      
E
ester.zhou 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
      @Entry
      @Component
      struct Index {
        @State imgDatas: string[] = [];
        // Obtain the image URL set.
        getAllImg() {
          let result = new Array<string>();
          try {
            let PhotoSelectOptions = new picker.PhotoSelectOptions();
            PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
            PhotoSelectOptions.maxSelectNumber = 5;
            let photoPicker = new picker.PhotoViewPicker();
            photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
              this.imgDatas = PhotoSelectResult.photoUris;
              console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
            }).catch((err) => {
              console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
            });
          } catch (err) {
            console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`);    }
        }
E
ester.zhou 已提交
104
      
E
ester.zhou 已提交
105
        // Call the preceding function in aboutToAppear to obtain the image URL set and store the URLs in imgDatas.
E
ester.zhou 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        async aboutToAppear() {
          this.getAllImg();
        }
        // Use the URL of imgDatas to load the image.
        build() {
          Column() {
            Grid() {
              ForEach(this.imgDatas, item => {
                GridItem() {
                  Image(item)
                    .width(200)
                }
              }, item => JSON.stringify(item))
            }
          }.width('100%').height('100%')
        }
      }
      ```
E
ester.zhou 已提交
124

E
ester.zhou 已提交
125
  2. Check the format of the URL obtained from the media library:
E
ester.zhou 已提交
126
      ```ts
E
ester.zhou 已提交
127
      Image('file://media/Photos/5')
E
ester.zhou 已提交
128 129 130
      .width(200)
      ```

E
ester.zhou 已提交
131
- Base64
E
ester.zhou 已提交
132

E
ester.zhou 已提交
133
  As shown above, the URL format is data:image/[png|jpeg|bmp|webp];base64,[base64 data], where **[base64 data]** indicates a Base64 string.
E
ester.zhou 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

  Base64 strings are widely used on web pages for storing pixel data of images.


### Pixel Map

A pixel map is a pixel image obtained after image decoding. For details, see [Image Development](../media/image-overview.md). In the following example, the data returned by the loaded online image is decoded into a pixel map, which is then displayed on the **\<Image>** component.

1. Create a **PixelMap** state variable.

   ```ts
   @State image: PixelMap = undefined;
   ```

2. Reference multimedia.
E
ester.zhou 已提交
149

E
ester.zhou 已提交
150 151
   Request an online image and implement transcoding to generate a pixel map.

E
ester.zhou 已提交
152
   1. Reference the network and media library access permissions.
E
ester.zhou 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
       ```ts
       import http from '@ohos.net.http';
       import ResponseCode from '@ohos.net.http';
       import image from '@ohos.multimedia.image';
       ```
   2. Enter the online image address.
       ```ts
       http.createHttp().request("https://www.example.com/xxx.png",
         (error, data) => {
           if (error){
             console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
           } else {
           }
         }
       )
       ```
E
ester.zhou 已提交
169
   3. Transcode the data returned by the online image address to a pixel map.  
E
ester.zhou 已提交
170 171
       ```ts
       let code = data.responseCode;
E
ester.zhou 已提交
172 173 174
       if (ResponseCode.ResponseCode.OK === code) {
         let res: any = data.result  
         let imageSource = image.createImageSource(res);
E
ester.zhou 已提交
175
         let options = {
E
ester.zhou 已提交
176 177 178 179 180 181 182
           alphaType: 0, // Alpha type.
           editable: false, // Whether the image is editable.
           pixelFormat: 3, // Pixel format.
           scaleMode: 1, // Scale mode.
           size: { height: 100, width: 100 }
         }  // Image size.
         imageSource.createPixelMap(options).then((pixelMap) => {
E
ester.zhou 已提交
183
           this.image = pixelMap
E
ester.zhou 已提交
184 185
         })
       }
E
ester.zhou 已提交
186 187 188 189 190 191 192 193 194 195 196
       ```
   4. Display the image.
       ```ts
       Button ("Get Online Image")
         .onClick(() => {
           this.httpRequest()
         })
       Image(this.image).height(100).width(100)
       ```


E
ester.zhou 已提交
197
## Displaying Vector Images
E
ester.zhou 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

The **\<Image>** component can display vector images in SVG format. The supported SVG labels are **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**.

You can use the **fillColor** attribute to change the fill color of an SVG image.


```ts
Image($r('app.media.cloud')).width(50)
.fillColor(Color.Blue) 
```

  **Figure 3** Original image 

![screenshot_20230223_141141](figures/screenshot_20230223_141141.png)

  **Figure 4** SVG image after the fill color is set 

![screenshot_20230223_141404](figures/screenshot_20230223_141404.png)


E
ester.zhou 已提交
218
## Setting Attributes
E
ester.zhou 已提交
219

E
ester.zhou 已提交
220
Setting attributes for the **\<Image>** component can spruce up the image with custom effects. The following are usage examples of common attributes. For details about all attributes, see [Image](../reference/arkui-ts/ts-basic-components-image.md).
E
ester.zhou 已提交
221 222 223 224


### Setting the Image Scale Mode

E
ester.zhou 已提交
225
You can use the **objectFit** attribute to scale an image to fit it into a container whose height and width are determined.
E
ester.zhou 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273


```ts
@Entry
@Component
struct MyComponent {
  scroller: Scroller = new Scroller()

  build() {
    Scroll(this.scroller) {
      Row() {
        Image($r('app.media.img_2')).width(200).height(150)
          .border({ width: 1 })
          .objectFit(ImageFit.Contain).margin(15) // The image is scaled with its aspect ratio retained to fit within the display boundaries.
          .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_img_2')).width(200).height(150)
          .border({ width: 1 })
          .objectFit(ImageFit.Cover).margin(15)
          // The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.
          .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_2')).width(200).height(150)
          .border({ width: 1 })
            // The image is scaled automatically to fit the display area.
          .objectFit(ImageFit.Auto).margin(15)
          .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
      Row() {
        Image($r('app.media.img_2')).width(200).height(150)
          .border({ width: 1 })
          .objectFit(ImageFit.Fill).margin(15)
          // The image is scaled to fill the display area, and its aspect ratio is not retained.
          .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_2')).width(200).height(150)
          .border({ width: 1 })
          // The image content is displayed with its aspect ratio retained. The size is smaller than or equal to the original size.
          .objectFit(ImageFit.ScaleDown).margin(15)
          .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.img_2')).width(200).height(150)
          .border({ width: 1 })
          // The original size is retained.
          .objectFit(ImageFit.None).margin(15)
          .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }
  }
}
```

E
ester.zhou 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
![en-us_image_0000001622804833](figures/en-us_image_0000001622804833.png)


### Using Image Interpolation

An image of low resolution may suffer quality loss with aliasing when scaled up. If this is the case, you can use the **interpolation** attribute to conduct image interpolation and improve image quality.


```ts
@Entry
@Component
struct Index {
  build() {
    Column() {
      Row() {
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.None)
          .borderWidth(1)
          .overlay("Interpolation.None", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.Low)
          .borderWidth(1)
          .overlay("Interpolation.Low", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)

      Row() {
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.Medium)
          .borderWidth(1)
          .overlay("Interpolation.Medium", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.High)
          .borderWidth(1)
          .overlay("Interpolation.High", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
  }
}
```

![en-us_image_0000001643127365](figures/en-us_image_0000001643127365.png)


### Setting Image Repeat Pattern

You can use the **objectRepeat** attribute to set the repeat pattern of an image. For details, see [ImageRepeat](../reference/arkui-ts/ts-appendix-enums.md#imagerepeat).


```ts
@Entry
@Component
struct MyComponent {
  build() {
    Column({ space: 10 }) {
      Row({ space: 5 }) {
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.XY)
          .objectFit(ImageFit.ScaleDown)
          // Repeat the image along both the horizontal and vertical axes.
          .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.Y)
          .objectFit(ImageFit.ScaleDown)
          // Repeat the image only along the vertical axis.
          .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.X)
          .objectFit(ImageFit.ScaleDown)
          // Repeat the image only along the horizontal axis.
          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding(8)
  }
}
```

![en-us_image_0000001593444112](figures/en-us_image_0000001593444112.png)


### Setting Image Rendering Mode

You can use the **renderMode** attribute to set the rendering mode of an image.


```ts
@Entry
@Component
struct MyComponent {
  build() {
    Column({ space: 10 }) {
      Row({ space: 50 }) {
        Image($r('app.media.example'))
          // Set the rendering mode to Original.
          .renderMode(ImageRenderMode.Original)
          .width(100)
          .height(100)
          .border({ width: 1 })
            // overlay is a universal attribute, which is used to add overlay text on the component.
          .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.example'))
          // Set the rendering mode to Template.
          .renderMode(ImageRenderMode.Template)
          .width(100)
          .height(100)
          .border({ width: 1 })
          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding({ top: 20,right: 10 })
  }
}
```

![en-us_image_0000001593293100](figures/en-us_image_0000001593293100.png)


### Setting Image Decoding Size

You can use the **sourceSize** attribute to set the image decoding size. By setting the decoding size to lower than the source size, you can decrease the image resolution.

In this example, the source image size is 1280 x 960, and the decoding size is 150 x 100 and 400 x 400.


```ts
@Entry
@Component
struct Index {
  build() {
    Column() {
      Row({ space: 20 }) {
        Image($r('app.media.example'))
          .sourceSize({
            width: 150,
            height: 150
          })
          .objectFit(ImageFit.ScaleDown)
          .width('25%')
          .aspectRatio(1)
          .border({ width: 1 })
          .overlay('width:150 height:150', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
        Image($r('app.media.example'))
          .sourceSize({
            width: 400,
            height: 400
          })
          .objectFit(ImageFit.ScaleDown)
          .width('25%')
          .aspectRatio(1)
          .border({ width: 1 })
          .overlay('width:400 height:400', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
      }.height(150).width('100%').padding(20)

    }
  }
}
```

![en-us_image_0000001593769844](figures/en-us_image_0000001593769844.png)


### Adding a Filter to an Image

You can use the **colorFilter** attribute to add a filter to an image.


```ts
@Entry
@Component
struct Index {
  build() {
    Column() {
      Row() {
        Image($r('app.media.example'))
          .width('40%')
          .margin(10)
        Image($r('app.media.example'))
          .width('40%')
          .colorFilter(
            [1, 1, 0, 0, 0,
             0, 1, 0, 0, 0,
             0, 0, 1, 0, 0,
             0, 0, 0, 1, 0])
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)
    }
  }
}
```

![en-us_image_0000001643171357](figures/en-us_image_0000001643171357.png)
E
ester.zhou 已提交
484 485 486 487


### Synchronously Loading Images

E
ester.zhou 已提交
488
Generally, the image loading process is performed asynchronously to avoid blocking the main thread and to streamline UI interaction. In certain cases, however, the image may flicker when refreshed. If this occurs, you can use the **syncLoad** attribute to load the image synchronously to avoid flickering. Avoid using this attribute if the image loading may take a long time. Otherwise, the page may fail to respond.
E
ester.zhou 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544


```ts
Image($r('app.media.icon'))
  .syncLoad(true)
```


## Adding Events

By binding the **onComplete** event to the **\<Image>** component, you can obtain necessary information about the image after the image is successfully loaded. You can also bind the **onError** event to obtain error information when the image fails to be loaded.


```ts
@Entry
@Component
struct MyComponent {
  @State widthValue: number = 0
  @State heightValue: number = 0
  @State componentWidth: number = 0
  @State componentHeight: number = 0

  build() {
    Column() {
      Row() {
        Image($r('app.media.ic_img_2'))
          .width(200)
          .height(150)
          .margin(15)
          .onComplete((msg: {
            width: number,
            height: number,
            componentWidth: number,
            componentHeight: number
          }) => {
            this.widthValue = msg.width
            this.heightValue = msg.height
            this.componentWidth = msg.componentWidth
            this.componentHeight = msg.componentHeight
          })
            // If the image fails to be obtained, print the result.
          .onError(() => {
            console.info('load image fail')
          })
          .overlay('\nwidth: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '\ncomponentWidth: ' + String(this.componentWidth) + '\ncomponentHeight: ' + String(this.componentHeight), {
            align: Alignment.Bottom,
            offset: { x: 0, y: 60 }
          })
      }
    }
  }
}
```


![en-us_image_0000001511740460](figures/en-us_image_0000001511740460.png)