Loading [MathJax]/jax/output/HTML-CSS/jax.js
1.4K Star 7.4K Fork 8.2K

OpenHarmony/docs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
docker
en
zh-cn
application-dev
IDL
account
ads-service/oaid
ai
application-models
application-test
arkts-utils
communication
connectivity
database
device-usage-statistics
device
dfx
faqs
file-management
internationalization
key-features/multi-device-app-dev
kit-readme
media
napi
notification
performance
public_sys-resources
quick-start
reference
apis
arkui-js-lite
arkui-js
arkui-ts
figures
public_sys-resources
Readme-CN.md
ohos-arkui-advanced-counter.md
ohos-arkui-advanced-popup.md
ohos-arkui-advanced-segmentbutton.md
ohos-multimedia-avcastpicker.md
ts-animatorproperty.md
ts-appendix-enums.md
ts-basic-components-blank.md
ts-basic-components-button.md
ts-basic-components-calendarpicker.md
ts-basic-components-checkbox.md
ts-basic-components-checkboxgroup.md
ts-basic-components-component3d.md
ts-basic-components-datapanel.md
ts-basic-components-datepicker.md
ts-basic-components-divider.md
ts-basic-components-formcomponent.md
ts-basic-components-gauge.md
ts-basic-components-image.md
ts-basic-components-imageanimator.md
ts-basic-components-imagespan.md
ts-basic-components-loadingprogress.md
ts-basic-components-marquee.md
ts-basic-components-menu.md
ts-basic-components-menuitem.md
ts-basic-components-menuitemgroup.md
ts-basic-components-navdestination.md
ts-basic-components-navigation.md
ts-basic-components-navrouter.md
ts-basic-components-patternlock.md
ts-basic-components-plugincomponent.md
ts-basic-components-progress.md
ts-basic-components-qrcode.md
ts-basic-components-radio.md
ts-basic-components-rating.md
ts-basic-components-remotewindow.md
ts-basic-components-richeditor.md
ts-basic-components-richtext.md
ts-basic-components-scrollbar.md
ts-basic-components-search.md
ts-basic-components-select.md
ts-basic-components-slider.md
ts-basic-components-span.md
ts-basic-components-stepper.md
ts-basic-components-stepperitem.md
ts-basic-components-text.md
ts-basic-components-textarea.md
ts-basic-components-textclock.md
ts-basic-components-textinput.md
ts-basic-components-textpicker.md
ts-basic-components-texttimer.md
ts-basic-components-timepicker.md
ts-basic-components-toggle.md
ts-basic-components-web.md
ts-basic-components-xcomponent.md
ts-basic-gestures-longpressgesture.md
ts-basic-gestures-pangesture.md
ts-basic-gestures-pinchgesture.md
ts-basic-gestures-rotationgesture.md
ts-basic-gestures-swipegesture.md
ts-basic-gestures-tapgesture.md
ts-canvasrenderingcontext2d.md
ts-combined-gestures.md
ts-components-canvas-canvas.md
ts-components-canvas-canvasgradient.md
ts-components-canvas-canvaspattern.md
ts-components-canvas-imagebitmap.md
ts-components-canvas-imagedata.md
ts-components-canvas-matrix2d.md
ts-components-canvas-path2d.md
ts-components-offscreencanvas.md
ts-components-summary.md
ts-composite-components-chip.md
ts-composite-components-composelistitem.md
ts-composite-components-composetitlebar.md
ts-composite-components-dialog.md
ts-composite-components-editabletitlebar.md
ts-composite-components-filter.md
ts-composite-components-progressbutton.md
ts-composite-components-selectionmenu.md
ts-composite-components-selecttitlebar.md
ts-composite-components-splitlayout.md
ts-composite-components-subheader.md
ts-composite-components-swiperefresher.md
ts-composite-components-tabtitlebar.md
ts-composite-components-toolbar.md
ts-composite-components-treeview.md
ts-container-ability-component.md
ts-container-alphabet-indexer.md
ts-container-badge.md
ts-container-column.md
ts-container-columnsplit.md
ts-container-counter.md
ts-container-effectcomponent.md
ts-container-flex.md
ts-container-flowitem.md
ts-container-folderstack.md
ts-container-formlink.md
ts-container-grid.md
ts-container-gridcol.md
ts-container-gridcontainer.md
ts-container-griditem.md
ts-container-gridrow.md
ts-container-hyperlink.md
ts-container-list.md
ts-container-listitem.md
ts-container-listitemgroup.md
ts-container-navigator.md
ts-container-panel.md
ts-container-refresh.md
ts-container-relativecontainer.md
ts-container-row.md
ts-container-rowsplit.md
ts-container-scroll.md
ts-container-sidebarcontainer.md
ts-container-stack.md
ts-container-swiper.md
ts-container-tabcontent.md
ts-container-tabs.md
ts-container-ui-extension-component.md
ts-container-waterflow.md
ts-custom-component-api.md
ts-custom-component-lifecycle.md
ts-drawing-components-circle.md
ts-drawing-components-ellipse.md
ts-drawing-components-line.md
ts-drawing-components-path.md
ts-drawing-components-polygon.md
ts-drawing-components-polyline.md
ts-drawing-components-rect.md
ts-drawing-components-shape.md
ts-explicit-animatetoimmediately.md
ts-explicit-animation.md
ts-gesture-customize-judge.md
ts-gesture-settings.md
ts-keyframeAnimateTo.md
ts-media-components-video.md
ts-methods-action-sheet.md
ts-methods-alert-dialog-box.md
ts-methods-calendarpicker-dialog.md
ts-methods-custom-dialog-box.md
ts-methods-datepicker-dialog.md
ts-methods-menu.md
ts-methods-textpicker-dialog.md
ts-methods-timepicker-dialog.md
ts-motion-path-animation.md
ts-offscreencanvasrenderingcontext2d.md
ts-page-transition-animation.md
ts-particle-animation.md
ts-pixel-units.md
ts-security-components-locationbutton.md
ts-security-components-pastebutton.md
ts-security-components-savebutton.md
ts-securitycomponent-attributes.md
ts-state-management.md
ts-transition-animation-component.md
ts-transition-animation-geometrytransition.md
ts-transition-animation-shared-elements.md
ts-types.md
ts-universal-attributes-accessibility.md
ts-universal-attributes-attribute-modifier.md
ts-universal-attributes-background.md
ts-universal-attributes-border-image.md
ts-universal-attributes-border.md
ts-universal-attributes-click-effect.md
ts-universal-attributes-click.md
ts-universal-attributes-component-id.md
ts-universal-attributes-cursor.md
ts-universal-attributes-drag-drop.md
ts-universal-attributes-enable.md
ts-universal-attributes-expand-safe-area.md
ts-universal-attributes-flex-layout.md
ts-universal-attributes-focus.md
ts-universal-attributes-foreground-blur-style.md
ts-universal-attributes-foreground-color.md
ts-universal-attributes-gradient-color.md
ts-universal-attributes-grid.md
ts-universal-attributes-hit-test-behavior.md
ts-universal-attributes-hover-effect.md
ts-universal-attributes-image-effect.md
ts-universal-attributes-layout-constraints.md
ts-universal-attributes-location.md
ts-universal-attributes-menu.md
ts-universal-attributes-modal-transition.md
ts-universal-attributes-monopolize-events.md
ts-universal-attributes-obscured.md
ts-universal-attributes-on-child-touch-test.md
ts-universal-attributes-opacity.md
ts-universal-attributes-outline.md
ts-universal-attributes-overlay.md
ts-universal-attributes-polymorphic-style.md
ts-universal-attributes-popup.md
ts-universal-attributes-renderfit.md
ts-universal-attributes-restoreId.md
ts-universal-attributes-sharp-clipping.md
ts-universal-attributes-sheet-transition.md
ts-universal-attributes-size.md
ts-universal-attributes-text-style.md
ts-universal-attributes-touch-target.md
ts-universal-attributes-transformation.md
ts-universal-attributes-use-effect.md
ts-universal-attributes-visibility.md
ts-universal-attributes-z-order.md
ts-universal-component-area-change-event.md
ts-universal-component-visible-area-change-event.md
ts-universal-events-click.md
ts-universal-events-drag-drop.md
ts-universal-events-key.md
ts-universal-events-keyboardshortcut.md
ts-universal-events-show-hide.md
ts-universal-events-touch.md
ts-universal-focus-event.md
ts-universal-mouse-key.md
errorcodes
figures
js-service-widget-ui
native-apis
native-lib
Readme-CN.md
native-api-intro.md
syscap-list.md
syscap.md
security
task-management
telephony
tools
ui
web
webgl
windowmanager
Readme-CN.md
Samples.md
application-dev-guide-for-gitee.md
application-dev-guide.md
website.md
contribute
design
device-dev
figures
readme
release-notes
third-party-cases
third-party-components
Legal-Notices.md
OpenHarmony-Overview_zh.md
glossary.md
readme.md
website.md
.gitattributes
.gitignore
CODEOWNERS
DCO.txt
LICENSE
OAT.xml
README.md
README_zh.md
image.png
克隆/下载
ts-basic-components-image.md 20.34 KB
一键复制 编辑 原始数据 按行查看 历史
zhounie 提交于 1年前 . 文档优化整改

Image

Image为图片组件,常用于在应用中显示图片。Image支持加载PixelMapResourceStrDrawableDescriptor类型的数据源,支持png、jpg、jpeg、bmp、svg、webp和gif类型的图片格式。

说明:

该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

需要权限

使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考声明权限

子组件

接口

Image(src: PixelMap | ResourceStr | DrawableDescriptor)

通过图片数据源获取图片,用于后续渲染展示。

Image组件加载图片失败或图片尺寸为0时,图片组件大小自动为0,不跟随父组件的布局约束。

从API version 9开始,该接口支持在ArkTS卡片中使用。

参数:

参数名 参数类型 必填 参数描述
src PixelMap | ResourceStrDrawableDescriptor 图片的数据源,支持本地图片和网络图片,引用方式请参考加载图片资源
1. PixelMap格式为像素图,常用于图片编辑的场景。
2. ResourceStr包含Resource和string格式。
string格式可用于加载网络图片和本地图片,常用于加载网络图片。当使用相对路径引用本地图片时,例如Image("common/test.jpg"),不支持跨包/跨模块调用该Image组件,建议使用Resource格式来管理需全局使用的图片资源。
- 支持Base64字符串。格式data:image/[png|jpeg|bmp|webp];base64,[base64 data], 其中[base64 data]Base64字符串数据。
- 支持file://路径前缀的字符串,应用沙箱URI:file://<bundleName>/<sandboxPath>。用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。
Resource格式可以跨包/跨模块访问资源文件,是访问本地图片的推荐方式。
3. 当传入资源id或name为普通图片时,生成DrawableDescriptor对象。
说明:
- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。
- ArkTS卡片上不支持http://等网络相关路径前缀和file://路径前缀的字符串。
- ArkTS卡片上不支持 PixelMap类型。
- 加载本地图片过程中,如果对图片进行修改或者替换,可能会引起应用崩溃。因此需要覆盖图片文件时,应该先删除该文件再重新创建一个同名文件。
- 网络图片必须支持RFC 9113标准,否则会导致加载失败。

属性

属性的详细使用指导请参考添加属性。除支持通用属性外,还支持以下属性:

名称 参数类型 描述
alt string | Resource 加载时显示的占位图,支持本地图片(png、jpg、bmp、svg和gif类型),不支持网络图片。
默认值:null
从API version 9开始,该接口支持在ArkTS卡片中使用。
objectFit ImageFit 设置图片的填充效果。
默认值:ImageFit.Cover
从API version 9开始,该接口支持在ArkTS卡片中使用。
objectRepeat ImageRepeat 设置图片的重复样式。从中心点向两边重复,剩余空间不足放下一张图片时会截断。
默认值:ImageRepeat.NoRepeat
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
svg类型图源不支持该属性。
interpolation ImageInterpolation 设置图片的插值效果,即缓解图片在缩放时的锯齿问题。
默认值:ImageInterpolation.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
svg类型图源不支持该属性。
renderMode ImageRenderMode 设置图片的渲染模式为原色或黑白。
默认值:ImageRenderMode.Original
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
svg类型图源不支持该属性。
sourceSize {
width: number,
height: number
}
设置图片解码尺寸,降低图片的分辨率,常用于需要让图片显示尺寸比组件尺寸更小的场景。和ImageFit.None配合使用时可在组件内显示小图。
单位:vp
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
仅在目标尺寸小于图源尺寸时生效。
svg类型图源不支持该属性。
PixelMap资源不支持该属性。
matchTextDirection boolean 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。
fitOriginalSize boolean 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。
fillColor ResourceColor 设置填充颜色,设置后填充颜色会覆盖在图片上。
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
仅对svg图源生效,设置后会替换svg图片的填充颜色。
autoResize boolean 设置图片解码过程中是否对图源自动缩放。设置为true时,组件会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。如原图大小为1920x1080,而显示区域大小为200x200,则图片会降采样解码到200x200的尺寸,大幅度节省图片占用的内存。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
降采样解码时图片的部分信息丢失,因此可能会导致图片质量的下降(如:出现锯齿),这时可以选择把autoResize设为false,按原图尺寸解码,提升显示效果。
syncLoad8+ boolean 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
建议加载尺寸较小的本地图片时将syncLoad设为true,因为耗时较短,在主线程上执行即可。
copyOption9+ CopyOptions 设置图片是否可复制。
当copyOption设置为非CopyOptions.None时,支持使用长按、鼠标右击、快捷组合键'CTRL+C'等方式进行复制。
默认值:CopyOptions.None
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
svg图片不支持复制。
colorFilter9+ ColorFilter 给图像设置颜色滤镜效果,入参为一个的4x5的RGBA转换矩阵。
矩阵第一行表示R(红色)的向量值,第二行表示G(绿色)的向量值,第三行表示B(蓝色)的向量值,第四行表示A(透明度)的向量值,4行分别代表不同的RGBA的向量值。
当矩阵对角线值为1,其余值为0时,保持图片原有色彩。
计算规则:
如果输入的滤镜矩阵为:
image-matrix-1
像素点为[R, G, B, A]
则过滤后的颜色为 [R’, G’, B’, A’]
image-matrix-2
从API version 9开始,该接口支持在ArkTS卡片中使用。
说明:
svg类型图源不支持该属性。
draggable9+ boolean 设置组件默认拖拽效果,设置为true时,组件可拖拽。
不能和onDragStart事件同时使用。
默认值:false
说明:
API version 9的默认值为false,API version 10的默认值为true。
enableAnalyzer11+ boolean 设置组件支持AI分析,设置为true时,组件可进行AI分析。
不能和overlay属性同时使用,两者同时设置时overlay中CustomBuilder属性将失效。
默认值:false
说明:
该特性依赖设备能力。
分析图像要求是静态非矢量图,即svg、gif等图像类型不支持分析,支持传入PixelMap进行分析,目前仅支持RGBA_8888类型,使用方式见示例
alt占位图不支持分析,objectRepeat属性仅在ImageRepeat.NoRepeat下支持分析,隐私遮罩属性obscured打开时不支持分析。
基于完整原始图像进行分析,设置clip、margin、borderRadius、position和objectFit属性导致图像显示不完整,或使用renderMode设置蒙层,仍基于完整原始图像进行分析。
copyOption属性不影响AI分析功能。
analyzerConfig11+ ImageAnalyzerConfig 设置AI分析类型,包括主体识别和文字识别功能,默认全部开启。
说明:
分析类型不支持动态修改。
系统接口:
此接口为系统接口。
edgeAntialiasing11+ number 设置SVG图源抗锯齿效果,仅对svg图源生效。
取值范围:[0.333,1.333],有效数字保留小数点后3位。
默认值:0

说明:

  • 使用快捷组合键对Image组件复制时,Image组件必须处于获焦状态。Image组件默认不获焦,需将focusable属性设置为true,即可使用TAB键将焦点切换到组件上,再将focusOnTouch属性设置为true,即可实现点击获焦。
  • 图片设置为svg图源时,当前支持的标签是svg、rect、circle、ellipse、path、line、polyline和polygon。

ImageInterpolation

从API version 9开始,该接口支持在ArkTS卡片中使用。

名称 描述
None 不使用图片插值。
High 高图片插值,插值质量最高,可能会影响图片渲染的速度。
Medium 中图片插值。
Low 低图片插值。

ImageRenderMode

从API version 9开始,该接口支持在ArkTS卡片中使用。

名称 描述
Original 原色渲染模式。
Template 黑白渲染模式。

ImageAnalyzerConfig11+

从API version 11开始,该接口支持在ArkTS卡片中使用。

图片AI分析类型配置。

系统接口: 此接口为系统接口。

系统能力: SystemCapability.ArkUI.ArkUI.Full

名称 描述
SUBJECT 主体识别功能。
TEXT 文字识别功能。

事件

除支持通用事件外,还支持以下事件:

onComplete

onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number}) => void) }) => void)

图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。

从API version 9开始,该接口支持在ArkTS卡片中使用。

参数:

参数名 类型 说明
width number 图片的宽。
单位:像素
height number 图片的高。
单位:像素
componentWidth number 组件的宽。
单位:像素
componentHeight number 组件的高。
单位:像素
loadingStatus number 图片加载成功的状态值。
说明:
返回的状态值为0时,表示图片数据加载成功。返回的状态值为1时,表示图片解码成功。
contentWidth10+ number 图片实际绘制的宽度。
单位:像素
说明:
仅在loadingStatus返回1时有效。
contentHeight10+ number 图片实际绘制的高度。
单位:像素
说明:
仅在loadingStatus返回1时有效。
contentOffsetX10+ number 实际绘制内容相对于组件自身的x轴偏移。
单位:像素
说明:
仅在loadingStatus返回1时有效。
contentOffsetY10+ number 实际绘制内容相对于组件自身的y轴偏移。
单位:像素
说明:
仅在loadingStatus返回1时有效。

onError

onError(callback: ImageErrorCallback)

图片加载异常时触发该回调。

从API version 9开始,该接口支持在ArkTS卡片中使用。

参数:

参数名 类型 说明
callback ImageErrorCallback 图片加载异常时触发的回调。

onFinish

onFinish(event: () => void)

当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。

仅支持svg格式的图片。

从API version 9开始,该接口支持在ArkTS卡片中使用。

ImageErrorCallback11+

type ImageErrorCallback = (error: ImageError) => void

图片加载异常时触发的回调。

参数名 类型 说明
error ImageError 图片加载异常时触发回调的返回对象。

ImageError11+

图片加载异常时触发回调的返回对象。

参数名 类型 说明
componentWidth number 组件的宽。
单位:像素
componentHeight number 组件的高。
单位:像素
message string 报错信息。

示例

加载基本类型图片

@Entry
@Component
struct ImageExample1 {
  build() {
    Column() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
        Row() {
          // 加载png格式图片
          Image($r('app.media.ic_camera_master_ai_leaf'))
            .width(110).height(110).margin(15)
            .overlay('png', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          // 加载gif格式图片
          Image($r('app.media.loading'))
            .width(110).height(110).margin(15)
            .overlay('gif', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
        Row() {
          // 加载svg格式图片
          Image($r('app.media.ic_camera_master_ai_clouded'))
            .width(110).height(110).margin(15)
            .overlay('svg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          // 加载jpg格式图片
          Image($r('app.media.ic_public_favor_filled'))
            .width(110).height(110).margin(15)
            .overlay('jpg', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
      }
    }.height(320).width(360).padding({ right: 10, top: 10 })
  }
}

zh-cn_image_0000001592882500

加载网络图片

加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用HTTP工具包发送网络请求,接着将返回的数据解码为Image组件中的PixelMap,图片开发可参考图片处理

使用网络图片时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考声明权限

@Entry
@Component
struct ImageExample2 {
  build() {
    Column({ space: 10 }) {
      Image("https://www.example.com/xxx.png")// 直接加载网络地址,请填写一个具体的网络图片地址
        .alt($r('app.media.icon'))// 使用alt,在网络图片加载成功前使用占位图
        .width(100)
        .height(100)
    }
  }
}

为图片添加事件

@Entry
@Component
struct ImageExample3 {
  private imageOne: Resource = $r('app.media.earth');
  private imageTwo: Resource = $r('app.media.star');
  private imageThree: Resource = $r('app.media.moveStar');
  @State src: Resource = this.imageOne
  @State src2: Resource = this.imageThree
  build(){
    Column(){
      //为图片添加点击事件,点击完成后加载特定图片
      Image(this.src)
        .width(100)
        .height(100)
        .onClick(() => {
          this.src = this.imageTwo
        })

      //当加载图片为SVG格式时
      Image(this.src2)
        .width(100)
        .height(100)
        .onClick(() => {
          //SVG动效播放完成时加载另一张图片
          this.src2 = this.imageOne
        })
    }.width('100%').height('100%')
  }
}

zh-cn_image_0000001607845173

使用PixelMap开启图像分析

import image from '@ohos.multimedia.image'
@Entry
@Component
struct ImageExample4 {
  @State imagePixelMap: image.PixelMap | undefined = undefined

  async aboutToAppear() {
    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
  }

  build() {
    Column() {
      Image(this.imagePixelMap)
        .enableAnalyzer(true)
        .width(200)
        .height(200)
    }
  }
  private async getPixmapFromMedia(resource: Resource) {
    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
      bundleName: resource.bundleName,
      moduleName: resource.moduleName,
      id: resource.id
    })
    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
    })
    await imageSource.release()
    return createPixelMap
  }
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
其他
1
https://gitee.com/openharmony/docs.git
git@gitee.com:openharmony/docs.git
openharmony
docs
docs
OpenHarmony-4.1-Beta1

搜索帮助