OpenHarmony应用开发-基础组件FormComponent/Gauge/Image
版本:v3.2 Release
FormComponent
提供卡片组件,实现卡片的显示功能。
说明:
- 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
 - 该组件为卡片组件的使用方,对应提供方的使用参考文档JS服务卡片UI组件。
 - 该组件使用需要具有系统签名。
 
权限
ohos.permission.GET_BUNDLE_INFO
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
ohos.permission.REQUIRE_FORM
子组件
无
接口
FormComponent(value: { id: number; name: string; bundle: string; ability: string; module: string; dimension?: FormDimension; temporary?: boolean })
创建卡片组件,用于显示提供的卡片。
参数:
参数名  | 参数类型  | 必填  | 参数描述  | 
id  | number  | 是  | 卡片标识(新建卡片填0)。  | 
name  | string  | 是  | 卡片名称。  | 
bundle  | string  | 是  | 目标卡片包名。  | 
ability  | string  | 是  | 目标卡片Ability名称。  | 
module  | string  | 是  | 卡片模块名称。  | 
dimension  | 否  | 卡片尺寸,支持2 * 2,4 * 4,4 * 2类型卡片。 默认值:Dimension_2_2。  | |
temporary  | boolean  | 否  | 卡片是否为临时卡片。  | 
FormDimension
名称  | 描述  | 
Dimension_1_2  | 1*2 卡片  | 
Dimension_2_2  | 2*2 卡片  | 
Dimension_2_4  | 2*4 卡片  | 
Dimension_4_4  | 4*4 卡片  | 
Dimension_2_19+  | 2*1 卡片  | 
属性
名称  | 参数类型  | 必填  | 描述  | 
size  | { width?: Length, height?: Length}  | 是  | 设置高宽尺寸。  | 
moduleName  | string  | 是  | 卡片模块名称。  | 
dimension  | 否  | 卡片尺寸,支持2 * 2,4 * 4,4 * 2类型卡片。 默认值:Dimension_2_2。  | |
allowUpdate  | boolean  | 否  | 是否允许卡片更新。 默认值:true。  | 
visibility  | 否  | 是否允许卡片可见。 默认值:Visible。  | 
事件
名称  | 功能描述  | 
onAcquired(callback: (info: { id: number }) => void)  | 获取到卡片后触发,返回卡片的id.  | 
onError(callback: (info: { errcode: number, msg: string }) => void)  | 组件加载错误回调。 errcode: 错误码。 msg: 错误信息。  | 
onRouter(callback: (info: any) => void)  | 组件路由事件回调,返回routerEvent中的信息。  | 
onUninstall(callback: (info: { id: number }) => void)  | 组件卸载回调,返回卸载卡片的id.  | 
示例
//card.ets
@Entry
@Component
struct CardExample {
   @State formId:number = 0;
  build() {
    Column() {
      Text('this is a card')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      FormComponent({
        id:this.formId,
        name:"Form1",
        bundle:"com.example.cardexample",
        ability:"FormAbility",
        module:"entry",
        dimension:FormDimension.Dimension_2_2,
        temporary:false
      })
        .allowUpdate(true)
        .size({width:360,height:360})
        .visibility(Visibility.Visible)
        .onAcquired((form)=>{
          console.log(`form info : ${JSON.stringify(form)}`);
          this.formId = form.id;
        })
        .onError((err)=>{
          console.log(`fail to add form, err: ${JSON.stringify(err)}`);
        })
    }
    .width('100%')
    .height('100%')
  }
}
Gauge
数据量规图表组件,用于将数据展示为环形图表。
说明:
该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
子组件
无
接口
Gauge(options:{value: number, min?: number, max?: number})
从API version 9开始,该接口支持在ArkTS卡片中使用。
参数:
参数名  | 参数类型  | 必填  | 参数描述  | 
value  | number  | 是  | 量规图的当前数据值,即图中指针指向位置。用于组件创建时量规图初始值的预置。  | 
min  | number  | 否  | 当前数据段最小值。 默认值:0  | 
max  | number  | 否  | 当前数据段最大值。 默认值:100  | 
属性
除支持通用属性外,还支持以下属性:
名称  | 参数类型  | 描述  | 
value  | number  | 设置量规图的数据值,可用于动态修改量规图的数据值。 默认值:0 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
startAngle  | number  | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。 默认值:0 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
endAngle  | number  | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。 默认值:360 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
colors  | Array<ColorStop>  | 设置量规图的颜色,支持分段颜色设置。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
strokeWidth  | Length  | 设置环形量规图的环形厚度。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
ColorStop
颜色断点类型,用于描述渐进色颜色断点。
从API version 9开始,该接口支持在ArkTS卡片中使用。
名称  | 类型定义  | 描述  | 
ColorStop  | [ResourceColor, number]  | 描述渐进色颜色断点类型,第一个参数为颜色值,若设置为非颜色类型,则置为黑色。第二个参数为颜色所占比重,若设置为负数或是非数值类型,则将比重置为0,该颜色不显示。  | 
示例
// xxx.ets
@Entry
@Component
struct GaugeExample {
  build() {
    Column({ space: 20 }) {
      // 使用默认的min和max为0-100,角度范围默认0-360,value值设置
      // 参数中设置当前值为75
      Gauge({ value: 75 })
        .width(200).height(200)
        .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]])
      
      // 参数设置当前值为75,属性设置值为25,属性设置优先级高
      Gauge({ value: 75 })
        .value(25) // 属性和参数都设置时以参数为准
        .width(200).height(200)
        .colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1]])
      
      // 210--150度环形图表
      Gauge({ value: 30, min: 0, max: 100 })
        .startAngle(210)
        .endAngle(150)
        .colors([[0x317AF7, 0.1], [0x5BA854, 0.2], [0xE08C3A, 0.3], [0x9C554B, 0.4]])
        .strokeWidth(20)
        .width(200)
        .height(200)
    }.width('100%').margin({ top: 5 })
  }
}
Image
图片组件,支持本地图片和网络图片的渲染展示。
说明:
该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
需要权限
使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考权限申请声明。
子组件
无
接口
Image(src: string | PixelMap | Resource)
通过图片数据源获取图片,用于后续渲染展示。
从API version 9开始,该接口支持在ArkTS卡片中使用。
参数:
参数名  | 参数类型  | 必填  | 参数描述  | 
src  | string| PixelMap | Resource  | 是  | 图片的数据源,支持本地图片和网络图片。 当使用相对路径引用图片资源时,例如 - 支持的图片格式包括png、jpg、bmp、svg和gif。 - 支持 - 支持 - 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 说明: - ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。 - ArkTS卡片上不支持 - ArkTS卡片上不支持 PixelMap类型  | 
属性
除支持通用属性外,还支持以下属性:
名称  | 参数类型  | 描述  | 
alt  | string | Resource  | 加载时显示的占位图,支持本地图片。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
objectFit  | 设置图片的缩放类型。 默认值:ImageFit.Cover 从API version 9开始,该接口支持在ArkTS卡片中使用。  | |
objectRepeat  | 设置图片的重复样式。 默认值:ImageRepeat.NoRepeat 从API version 9开始,该接口支持在ArkTS卡片中使用。 说明: svg类型图源不支持该属性。  | |
interpolation  | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。 默认值:ImageInterpolation.None 从API version 9开始,该接口支持在ArkTS卡片中使用。 说明: svg类型图源不支持该属性。 PixelMap资源不支持该属性。  | |
renderMode  | 设置图片渲染的模式。 默认值:ImageRenderMode.Original 从API version 9开始,该接口支持在ArkTS卡片中使用。 说明: svg类型图源不支持该属性。  | |
sourceSize  | { width: number, height: number }  | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。 从API version 9开始,该接口支持在ArkTS卡片中使用。 说明: PixelMap资源和SVG图片不支持该属性。  | 
matchTextDirection  | boolean  | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。 默认值:false 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
fitOriginalSize  | boolean  | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。 默认值:false 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
fillColor  | 填充颜色。设置的填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片的fill颜色。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | |
autoResize  | boolean  | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。 默认值:true 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
syncLoad8+  | boolean  | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。 默认值:false 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
copyOption9+  | 设置图片是否可复制(SVG图片不支持复制)。 当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键’CTRL+C’等方式进行复制。 默认值:CopyOptions.None 该接口支持在ArkTS卡片中使用。  | |
colorFilter9+  | 给图像设置颜色滤镜效果。 该接口支持在ArkTS卡片中使用。  | 
说明:
使用快捷组合键对Image组件复制的前提是,该组件必须处于获焦状态。将Image组件的属性focusable设置为true,即可使用TAB键将焦点切换到Image组件上,再将Image组件的focusOnTouch属性设置为true,即可实现点击获焦。 图片设置svg图源时,支持的标签范围有限,目前支持的svg标签包括svg、rect、circle、ellipse、path、line、polyline、polygon、animate。
ImageInterpolation
从API version 9开始,该接口支持在ArkTS卡片中使用。
名称  | 描述  | 
None  | 不使用插值图片数据。  | 
High  | 插值图片数据的使用率高,可能会影响图片渲染的速度。  | 
Medium  | 插值图片数据的使用率中。  | 
Low  | 插值图片数据的使用率低。  | 
ImageRenderMode
从API version 9开始,该接口支持在ArkTS卡片中使用。
名称  | 描述  | 
Original  | 按照原图进行渲染,包括颜色。  | 
Template  | 将图片渲染为模板图片,忽略图片的颜色信息。  | 
事件
除支持通用事件外,还支持以下事件:
名称  | 功能描述  | 
onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number }) => void)  | 图片成功加载时触发该回调,返回成功加载的图片尺寸。 - width:图片的宽,单位为像素。 - height:图片的高,单位为像素。 - componentWidth:组件的宽,单位为像素。 - componentHeight:组件的高,单位为像素。 - loadingStatus:图片加载成功的状态。 从API version 9开始,该接口支持在ArkTS卡片中使用。 说明: loadingStatus返回的状态值为0时,代表图片加载失败;返回的状态值为1时,代表图片加载成功。  | 
onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void)  | 图片加载出现异常时触发该回调。 - componentWidth:组件的宽,单位为像素。 - componentHeight:组件的高,单位为像素。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
onFinish(event: () => void)  | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。 从API version 9开始,该接口支持在ArkTS卡片中使用。  | 
示例
图片加载
加载显示不同类型的图片,并设置图片的缩放类型。
@Entry
@Component
struct ImageExample1 {
  private on: string = 'www.example.com' 
  @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 })
            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_gif'))
            .width(110).height(110).border({ width: 1 })
            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_svg'))
            .width(110).height(110).border({ width: 1 })
            .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 })
            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image(this.src)
            .width(110).height(110).border({ width: 1 })
            .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 })
            .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 })
            .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 })
            .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 })
            .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 })
            .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 })
  }
}
网络图片
加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用SDK中提供的HTTP工具包发送网络请求,接着将返回的数据解码为Image组件中的PixelMap,图片开发可参考图片处理。代码如下。
// @ts-nocheck
import http from '@ohos.net.http'
import ResponseCode from '@ohos.net.http'
import image from '@ohos.multimedia.image'
@Entry 
@Component 
struct Index {
    
  // 先创建一个PixelMap状态变量用于接收网络图片
  @State image: PixelMap = undefined
  build() {
    Column({space: 10}) {
      Button("获取网络图片")
        .onClick(() => {
          this.httpRequest()
        })
      Image(this.image).height(100).width(100)
    }
    .width('100%')
    .height('100%')
    .padding(10)
  }
  // 网络图片请求方法
  private httpRequest() {
    let httpRequest = http.createHttp()
	
    httpRequest.request(
      "https://www.example.com/xxx.png",   // 请填写一个具体的网络图片地址
      (error, data) => {
        if(error) {
          console.log("error code: " + error.code + ", msg: " + error.message)
        } else {
          let code = data.responseCode
          if(ResponseCode.ResponseCode.OK == code) {
            let imageSource = image.createImageSource(data.result)
            let options = {alphaType: 0,                     // 透明度
                           editable: false,                  // 是否可编辑
                           pixelFormat: 3,                   // 像素格式
                           scaleMode: 1,                     // 缩略值
                           size: {height: 100, width: 100}}  // 创建图片大小
            imageSource.createPixelMap(options).then((pixelMap) => {
              this.image = pixelMap
            })
          } else {
            console.log("response code: " + code)
          }
        }
      }
    )
  }
}说明:网络图片加载的请求方式、超时、额外请求参数等配置可以参考HTTP工具包中关于request()请求方法的细节。
设置属性
@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 })
          .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 })
          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
      
      Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
      Image('')
        .alt($r('app.media.Image_none'))
        .width(100).height(100).border({ width: 1 })
        
      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 })
          .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 })
          .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
      
      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 })
          .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 })
          .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 })
          .objectRepeat(ImageRepeat.X).objectFit(ImageFit.ScaleDown)
          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding({ right: 10 })
  }
}
事件调用
@Entry
@Component
struct ImageExample3 {
  @State widthValue: number = 0
  @State heightValue: number = 0
  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')
  @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)
            // 图片加载完成后,获取图片尺寸。
            .onComplete((msg: { width: number,height: number }) => {
              this.widthValue = msg.width
              this.heightValue = msg.height
            })
            .onError(() => {
              console.log('load image fail')
            })
            .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), {
              align: Alignment.Bottom,
              offset: { x: 0, y: 20 }
            })
        }
        // 为图片添加点击事件,点击完成后加载特定图片。
        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%')
  }
}
渲染沙箱路径图片
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
import context from '@ohos.app.ability.common';
@Entry
@Component
struct LoadImageExample {
  @State resourcesPath: string = ''
  @State sandboxPath: string = ''
  context: context.UIAbility = getContext(this) as context.UIAbilityContext
  build() {
    Column() {
      Button('读取沙箱图片')
        .margin({ bottom: 10, top: 10 })
        .onClick(() => {
          this.sandboxPath = this.context.getApplicationContext().filesDir + '/icon.png'
          console.log(`读取沙箱图片=========>${this.sandboxPath}`)
          let fd = fs.openSync(this.sandboxPath, 0o100)
          console.log(`create file========>${fd}`)
          let srcPath = this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
          console.log('mySrcpath' + srcPath)
          fileio.copyFileSync(srcPath, this.sandboxPath) // 复制图片到沙箱路径
          this.sandboxPath = 'file://' + this.context.getApplicationContext().filesDir + '/icon.png'
        })
      Button('读取资源图片')
        .margin({ bottom: 10 })
        .onClick(() => {
          this.resourcesPath = 'file://' + this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
        })
      Text(`资源图片路径:${this.resourcesPath}`)
        .fontSize(20)
        .margin({ bottom: 10 })
      Image(this.resourcesPath)
        .width(100)
        .height(100)
      Text(`沙箱图片路径:${this.sandboxPath}`)
        .fontSize(20)
        .margin({ bottom: 10 })
      Image(this.sandboxPath)
        .width(100)
        .height(100)
    }
    .width('100%').height('100%')
  }
}



















