1, 三种引入用法: Image(src: string | Resource | media.PixelMap)
①本地资源图片: 通过路径引入放在ets文件夹下的图片
Image('images/view.jpg') // Image('本地图片存放路径')
②网络资源图片: 需先申请网络权限ohos.permission.INTERNET
Image('https://www.example.com/example.JPG') // Image('被许可网络图片链接')
③Resource资源: resources下的图片资源均可通过$r('图片')的方式可跨包/跨模块引入![](https://img-blog.csdnimg.cn/direct/fc7aa46136834682afedf2b727a38b47.png)
![](https://img-blog.csdnimg.cn/direct/b4ce4a0ebc75408fab6b86420ee11b7b.png)
Image($r('app.media.icon')) // 注意获取图片语法格式
Image($rawfile('snap')) // 引入rawfile文件夹下的图片
④媒体库图片
媒体库file://data/storage,支持file://路径前缀的字符串,用于访问通过媒体库提供的图片路径。
// 1,通用
Image('file://media/Photos/5')
// 2,调接口获取图库照片集
import picker from '@ohos.file.picker';
@Entry
@Component
struct Index {
@State imgDatas: string[] = [];
// 获取照片url集
getAllImg() {
let result = new Array<string>();
try {
// 文档选择
let PhotoSelectOptions = new picker.PhotoSelectOptions();
// 可选择的媒体文件类型: IMAGE_TYPE(图片类型)/VIDEO_TYPE(视频类
// 型)/IMAGE_VIDEO_TYPE(图片和视频类型)
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
// 一次最多可选数量
PhotoSelectOptions.maxSelectNumber = 5;
// 图库选择器对象,用来支撑选择图片/视频和保存图片/视频等用户场景。在使用前,需要
// 先创建PhotoViewPicker实例
let photoPicker = new picker.PhotoViewPicker();
// 通过选择模式拉起photoPicker界面,用户可以选择一个或多个图片/视频。接口采用
// promise异步返回形式,传入可选参数PhotoSelectOptions对象,返回
// PhotoSelectResult对象。
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}`);
}
}
// aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
async aboutToAppear() {
this.getAllImg();
}
// 使用imgDatas的url加载图片。
build() {
Column() {
Grid() {
ForEach(this.imgDatas, item => {
GridItem() {
Image(item)
.width(200)
}
}, item => JSON.stringify(item))
}
}.width('100%').height('100%')
}
}
⑤base64
data:image/[png|jpeg|bmp|webp];base64,[base64 data]
2, 常用属性
①objectFit 图片缩放
// 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
.objectFit(ImageFit.Contain).margin(15)
// 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
.objectFit(ImageFit.Cover).margin(15)
// 自适应显示。
.objectFit(ImageFit.Auto).margin(15)
// 不保持宽高比进行放大缩小,使得图片充满显示边界。
.objectFit(ImageFit.Fill).margin(15)
// 保持宽高比显示,图片缩小或者保持不变。
.objectFit(ImageFit.ScaleDown).margin(15)
// 保持原有尺寸显示。
.objectFit(ImageFit.None).margin(15)
②interpolation 图片插值
当原图分辨率较低并且放大显示时,图片会模糊出现锯齿, 这时可以使用interpolation属性对图片进行插值,使图片显示得更清晰。
.interpolation(ImageInterpolation.None)
.interpolation(ImageInterpolation.Low)
.interpolation(ImageInterpolation.Medium)
.interpolation(ImageInterpolation.High)
③objectRepeat 设置图片的重复样式方式
// 在水平轴和竖直轴上同时重复绘制图片
.objectRepeat(ImageRepeat.XY)
// overlay是通用属性,用于在组件上显示说明文字
.overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 只在竖直轴上重复绘制图片
.objectRepeat(ImageRepeat.Y)
.overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 只在水平轴上重复绘制图片
.objectRepeat(ImageRepeat.X)
.overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 不重复绘制
.objectRepeat(ImageRepeat.NoRepeat)
④renderMode 设置图片的渲染模式为原色或黑白
// 设置图片的渲染模式为原色
.renderMode(ImageRenderMode.Original)
// overlay是通用属性,用于在组件上显示说明文字
.overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
// 设置图片的渲染模式为黑白
.renderMode(ImageRenderMode.Template)
.overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
⑤colorFilter 修改图片的像素颜色,为图片添加滤镜
.colorFilter(
[1, 1, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0])
⑥.syncLoad 同步加载图片
一般情况下,图片加载流程会异步进行,以避免阻塞主线程,影响UI交互。但是特定情况下,图片刷新时会出现闪烁,这时可以使用syncLoad属性,使图片同步加载,从而避免出现闪烁。不建议图片加载较长时间时使用,会导致页面无法响应。
Image($r('app.media.icon'))
.syncLoad(true)
3, onComplete & onError事件调用
.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')
})
4, 多媒体像素图
// 创建PixelMap状态变量
@State image: PixelMap = undefined;
// 引用网络权限与媒体库权限
import http from '@ohos.net.http';
import ResponseCode from '@ohos.net.http';
import image from '@ohos.multimedia.image';
// 填写网络图片地址
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 {
}
}
)
// 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
let code = data.responseCode;
if (ResponseCode.ResponseCode.OK === code) {
let res: any = data.result
let imageSource = image.createImageSource(res);
let options = {
alphaType: 0, // 透明度
editable: false, // 是否可编辑
pixelFormat: 3, // 像素格式
scaleMode: 1, // 缩略值
size: { height: 100, width: 100}
} // 创建图片大小
imageSource.createPixelMap(options).then((pixelMap) => {
this.image = pixelMap
})
}
// 显示图片。
Button("获取网络图片")
.onClick(() => {
this.httpRequest()
})
Image(this.image).height(100).width(100)