开发者经常需要在应用中显示一些图片,例如:按钮中的icon、网络图片、本地图片等。在应用中显示图片需要使用image组件实现,image支持多种图片格式,包括png、jpg、bmp、svg和gif,具体用法请参考 image 组件。
image通过调用接口来创建,接口调用形式如下:
image(src: pixelmap | resourcestr | drawabledescriptor)
该接口通过图片数据源获取图片,支持本地图片和网络图片的渲染展示。其中,src是图片的数据源,加载方式请参考 加载图片资源 。
加载图片资源
image支持加载存档图、多媒体像素图两种类型。
存档图类型数据源
存档图类型的数据源可以分为本地资源、网络资源、resource资源、媒体库资源和base64。
-
本地资源
创建文件夹,将本地图片放入ets文件夹下的任意位置。
image组件引入本地图片路径,即可显示图片(根目录为ets文件夹)。
image('images/view.jpg')
.width(200)
-
网络资源
引入网络图片需申请权限ohos.permission.internet,具体申请方式请参考 声明权限 。此时,image组件的src参数为网络图片的链接。
image组件首次加载网络图片时,需要请求网络资源,非首次加载时,默认从缓存中直接读取图片,更多图片缓存设置请参考 setimagecachecount 、 setimagerawdatacachesize 、 setimagefilecachesize。
image('https://www.example.com/example.jpg') // 实际使用时请替换为真实地址
-
resource资源
使用资源格式可以跨包/跨模块引入图片,resources文件夹下的图片都可以通过$r资源接口读 取到并转换到resource格式。
图1 resources
调用方式:
image($r('app.media.icon'))
还可以将图片放在rawfile文件夹下。
**图2** rawfile
调用方式:
image($rawfile('example1.png'))
-
媒体库file://data/storage
支持file://路径前缀的字符串,用于访问通过 媒体库 提供的图片路径。
- 调用接口获取图库的照片url。
import picker from '@ohos.file.picker';
import { businesserror } from '@ohos.base';
@entry
@component
struct index {
@state imgdatas: string[] = [];
// 获取照片url集
getallimg() {
try {
let photoselectoptions:picker.photoselectoptions = new picker.photoselectoptions();
photoselectoptions.mimetype = picker.photoviewmimetypes.image_type;
photoselectoptions.maxselectnumber = 5;
let photopicker:picker.photoviewpicker = new picker.photoviewpicker();
photopicker.select(photoselectoptions).then((photoselectresult:picker.photoselectresult) => {
this.imgdatas = photoselectresult.photouris;
console.info('photoviewpicker.select successfully, photoselectresult uri: ' + json.stringify(photoselectresult));
}).catch((err:error) => {
let message = (err as businesserror).message;
let code = (err as businesserror).code;
console.error(`photoviewpicker.select failed with. code: ${code}, message: ${message}`);
});
} catch (err) {
let message = (err as businesserror).message;
let code = (err as businesserror).code;
console.error(`photoviewpicker failed with. code: ${code}, message: ${message}`); }
}
// abouttoappear中调用上述函数,获取图库的所有图片url,存在imgdatas中
async abouttoappear() {
this.getallimg();
}
// 使用imgdatas的url加载图片。
build() {
column() {
grid() {
foreach(this.imgdatas, (item:string) => {
griditem() {
image(item)
.width(200)
}
}, (item:string):string => json.stringify(item))
}
}.width('100%').height('100%')
}
}
2.从媒体库获取的url格式通常如下。
image('file://media/photos/5')
.width(200)
-
base64
路径格式为data:image/[png|jpeg|bmp|webp];base64,[base64 data],其中[base64 data]为base64字符串数据。
base64格式字符串可用于存储图片的像素数据,在网页上使用较为广泛。
多媒体像素图
pixelmap是图片解码后的像素图,具体用法请参考 图片开发指导 。以下示例将加载的网络图片返回的数据解码成pixelmap格式,再显示在image组件上,
- 创建pixelmap状态变量。
@state image: pixelmap | undefined = undefined;
-
引用多媒体。
请求网络图片,解码编码pixelmap。
- 引用网络权限与媒体库权限。
import http from '@ohos.net.http';
import responsecode from '@ohos.net.http';
import image from '@ohos.multimedia.image';
import { businesserror } from '@ohos.base';
- 填写网络图片地址。
let outdata: http.httpresponse
http.createhttp().request("https://www.example.com/xxx.png",
(error: businesserror, data: http.httpresponse) => {
if (error) {
console.error(`http request failed with. code: ${error.code}, message: ${error.message}`);
} else {
outdata = data
}
}
)
- 将网络地址成功返回的数据,编码转码成pixelmap的图片格式。
let code: http.responsecode | number = outdata.responsecode
if (responsecode.responsecode.ok === code) {
let imagedata: arraybuffer = outdata.result as arraybuffer;
let imagesource: image.imagesource = image.createimagesource(imagedata);
class tmp {
height: number = 100
width: number = 100
}
let si: tmp = new tmp()
let options: record<string, number | boolean | tmp> = {
'alphatype': 0, // 透明度
'editable': false, // 是否可编辑
'pixelformat': 3, // 像素格式
'scalemode': 1, // 缩略值
'size': { height: 100, width: 100 }
} // 创建图片大小
class imagetmp {
image: pixelmap | undefined = undefined
set(val: pixelmap) {
this.image = val
}
}
imagesource.createpixelmap(options).then((pixelmap: pixelmap) => {
let im = new imagetmp()
im.set(pixelmap)
})
}
- 显示图片。
class htp{
httprequest: function | undefined = undefined
set(){
if(this.httprequest){
this.httprequest()
}
}
}
button("获取网络图片")
.onclick(() => {
let sethtp = new htp()
sethtp.set()
})
image(this.image).height(100).width(100)
显示矢量图
image组件可显示矢量图(svg格式的图片),支持的svg标签为:svg、rect、circle、ellipse、path、line、polyline、polygon和animate。
svg格式的图片可以使用fillcolor属性改变图片的绘制颜色。
image($r('app.media.cloud'))
.width(50)
.fillcolor(color.blue)
图3 原始图片
图4 设置绘制颜色后的svg图片
添加属性
给image组件设置属性可以使图片显示更灵活,达到一些自定义的效果。以下是几个常用属性的使用示例,完整属性信息详见 image 。
设置图片缩放类型
通过objectfit属性使图片缩放到高度和宽度确定的框内。
@entry
@component
struct mycomponent {
scroller: scroller = new scroller()
build() {
scroll(this.scroller) {
column() {
row() {
image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
.objectfit(imagefit.contain)
.margin(15)
.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)
// 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
.overlay('cover', { align: alignment.bottom, offset: { x: 0, y: 20 } })
image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 自适应显示。
.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)
// 不保持宽高比进行放大缩小,使得图片充满显示边界。
.overlay('fill', { align: alignment.bottom, offset: { x: 0, y: 20 } })
image($r('app.media.img_2'))
.width(200)
.height(150)
.border({ width: 1 })
// 保持宽高比显示,图片缩小或者保持不变。
.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 })
// 保持原有尺寸显示。
.objectfit(imagefit.none)
.margin(15)
.overlay('none', { align: alignment.bottom, offset: { x: 0, y: 20 } })
}
}
}
}
}
图片插值
当原图分辨率较低并且放大显示时,图片会模糊出现锯齿。这时可以使用interpolation属性对图片进行插值,使图片显示得更清晰。
@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%')
}
}
设置图片重复样式
通过objectrepeat属性设置图片的重复样式方式,重复样式请参考 imagerepeat 枚举说明。
@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)
// 在水平轴和竖直轴上同时重复绘制图片
.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)
// 只在竖直轴上重复绘制图片
.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)
// 只在水平轴上重复绘制图片
.overlay('imagerepeat.x', { align: alignment.bottom, offset: { x: 0, y: 20 } })
}
}.height(150).width('100%').padding(8)
}
}
设置图片渲染模式
通过rendermode属性设置图片的渲染模式为原色或黑白。
@entry
@component
struct mycomponent {
build() {
column({ space: 10 }) {
row({ space: 50 }) {
image($r('app.media.example'))
// 设置图片的渲染模式为原色
.rendermode(imagerendermode.original)
.width(100)
.height(100)
.border({ width: 1 })
// overlay是通用属性,用于在组件上显示说明文字
.overlay('original', { align: alignment.bottom, offset: { x: 0, y: 20 } })
image($r('app.media.example'))
// 设置图片的渲染模式为黑白
.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 })
}
}
设置图片解码尺寸
通过sourcesize属性设置图片解码尺寸,降低图片的分辨率。
原图尺寸为1280960,该示例将图片解码为4040和90*90。
@entry
@component
struct index {
build() {
column() {
row({ space: 50 }) {
image($r('app.media.example'))
.sourcesize({
width: 40,
height: 40
})
.objectfit(imagefit.scaledown)
.aspectratio(1)
.width('25%')
.border({ width: 1 })
.overlay('width:40 height:40', { align: alignment.bottom, offset: { x: 0, y: 40 } })
image($r('app.media.example'))
.sourcesize({
width: 90,
height: 90
})
.objectfit(imagefit.scaledown)
.width('25%')
.aspectratio(1)
.border({ width: 1 })
.overlay('width:90 height:90', { align: alignment.bottom, offset: { x: 0, y: 40 } })
}.height(150).width('100%').padding(20)
}
}
}
为图片添加滤镜效果
通过colorfilter修改图片的像素颜色,为图片添加滤镜。
@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)
}
}
}
同步加载图片
一般情况下,图片加载流程会异步进行,以避免阻塞主线程,影响ui交互。但是特定情况下,图片刷新时会出现闪烁,这时可以使用syncload属性,使图片同步加载,从而避免出现闪烁。不建议图片加载较长时间时使用,会导致页面无法响应。
image($r('app.media.icon'))
.syncload(true)
事件调用
通过在image组件上绑定oncomplete事件,图片加载成功后可以获取图片的必要信息。如果图片加载失败,也可以通过绑定onerror回调来获得结果。
@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 => {
if(msg){
this.widthvalue = msg.width
this.heightvalue = msg.height
this.componentwidth = msg.componentwidth
this.componentheight = msg.componentheight
}
})
// 图片获取失败,打印结果
.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 }
})
}
}
}
}
鸿蒙全栈开发全新学习指南
为了积极培养鸿蒙生态人才,让大家都能学习到鸿蒙开发最新的技术,针对一些在职人员、0基础小白、应届生/计算机专业、鸿蒙爱好者等人群,整理了一套纯血版鸿蒙(harmonyos next)全栈开发技术的学习路线【包含了大厂app实战项目开发】。
本路线共分为四个阶段:
第一阶段:鸿蒙初中级开发必备技能
第二阶段:鸿蒙南北双向高工技能基础:gitee.com/mnxiaona/733gh
第三阶段:应用开发中高级就业技术
第四阶段:全网首发-工业级南向设备开发就业技术:gitee.com/mnxiaona/733gh
《鸿蒙 (harmony os)开发学习手册》(共计892页)
如何快速入门?
1.基本概念
2.构建第一个arkts应用
3.……
开发基础知识:gitee.com/mnxiaona/733gh
1.应用基础知识
2.配置文件
3.应用数据管理
4.应用安全管理
5.应用隐私保护
6.三方应用调用管控机制
7.资源分类与访问
8.学习arkts语言
9.……
基于arkts 开发
1.ability开发
2.ui开发
3.公共事件与通知
4.窗口管理
5.媒体
6.安全
7.网络与链接
8.电话服务
9.数据管理
10.后台任务(background task)管理
11.设备管理
12.设备使用信息统计
13.dfx
14.国际化开发
15.折叠屏系列
16.……
鸿蒙开发面试真题(含参考答案):gitee.com/mnxiaona/733gh
鸿蒙入门教学视频:
美团app实战开发教学:gitee.com/mnxiaona/733gh
写在最后
- 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
- 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
- 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
- 想要获取更多完整鸿蒙最新学习资源,请移步前往小编:
gitee.com/mnxiaona/733gh
发表评论