HarmonyOS Image图片显示网络图片尺寸问题?

使用Image去显示接口返回的图片,想在获取图片拿到图片的宽高来设置图片的宽高,而不是直接写死图片的宽高,请问如何设置

阅读 505
1 个回答

可以试下通过将网络图片转换成PixelMap再通过getImageInfo方法获取图片的宽高,具体使用还请参考文档:

createImageSource:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#imagecreateimagesource9-2

createPixelMap:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#imagecreatepixelmap8

getImageInfo:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#getimageinfo7

http.createHttp()
  .request(url,
    async (error: BusinessError, data: http.HttpResponse) => {
      if (error) {
        console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
      } else {
        console.error('http reqeust success.');
        let imageData: ArrayBuffer = data.result as ArrayBuffer;
        let imageSource: image.ImageSource = image.createImageSource(imageData);
        console.error(`http reqeust size = ${imageData.byteLength}`);

        let options: image.DecodingOptions = { editable: true }

        this._pixelMap = await imageSource.createPixelMap(options);
        this._pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
          if (imageInfo == undefined) {
            console.error("Failed to obtain the image pixel map information.");
          }
          console.log('imageInfo=======', JSON.stringify(imageInfo))
          this.with = imageInfo.size.width;
          this.hig = imageInfo.size.height;
          console.log("zyc Succeeded in obtaining the image pixel map information.", this.with, this.hig);
        })
        console.error("zyc aboutToAppear end.");

      }
    })