本篇内容: 显示图片、自定义图形和画布自定义图形的学习使用
一、知识储备
1. 图片组件(Image)
- 可以展示jpg 、png 、svg 、gif等各格式的网络和本地资源文件图片的组件
- 接口调用
Image(src: string | Resource | media.PixelMap)
Image('images/view.jpg').width(200)//ets本次资源目录下
Image('https://www.example.com/example.JPG') // 网络图片实际使用时请替换为真实地址
Image($r('app.media.ic_hm_logo'))//resources/base/media目录下
Image($rawfile('snap'))//resources/rawfile目录下
Image('file://media/Photos/5').width(200)//手机媒体库中图片资源
//从手机媒体库中选择图片
try {
let photoSelectOptions = new picker.PhotoSelectOptions(); //媒体库选择器设置
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; //图片类型
photoSelectOptions.maxSelectNumber = 5; //最多 选取五张
let photoPicker = new picker.PhotoViewPicker; //初始化图片选择器
photoPicker.select(photoSelectOptions).then(photoSelectResult => { //选择结果回调
this.imgListData = photoSelectResult.photoUris;
console.error(`imgListData size is ${this.imgListData.length}`)
}).catch(err=>{
console.error(`select failed code is ${err.code}, msg : ${err.message}`)
})
} catch (err) {
console.error(`load photo failed ${err.code}, msg: ${err.message}`)
}
http.createHttp().request(this.imgUrl, (err, data) => {
if (err) {
console.error(`err is ${JSON.stringify(err)}`)
} else {
let code = data.responseCode;
if (ResponseCode.ResponseCode.OK == code) {
let res: any = data.result;
let imageSource = image.createImageSource(res)
let options = {
alphaTye: 0, //透明度
editable: false, //是否可编辑
pixelFormat: 3, //像素格式
scaleMode: 1, //缩略值
size: { height: 100, wight: 100 } //创建图片大小
}
imageSource.createPixelMap(options).then(pixelMap => {
this.image = pixelMap;
})
}
}
})
- 常用函数
- .objectFit(ImageFit.Fill)// 缩放类型
- .interpolation(ImageInterpolation.High)//图片插值,抗锯齿,使图片看着更清晰
- .renderMode(ImageRenderMode.Template) //图片渲染模式
- .objectRepeat(ImageRepeat.X)//设置图片在xy轴上重复显示
- .sourceSize({//设置图片解码尺寸
width: 65, height: 40
})
- .colorFilter([//添加滤镜效果
1,1,0,0,0,
0,1,0,0,0,
0,0,1,0,0,
0,0,0,1,0
])
- .syncLoad(true)//同步加载图片
- .onComplete(msg=>{ 加载成功和失败的事件回调
if (msg) {
console.error(widthVal = ${msg.width}\n height = ${msg.height} \n componentW = ${msg.componentWidth} \n status = ${msg.loadingStatus})
}
})
.onError(()=>{
console.error(‘err’)
})
2. 自定义图形(shape)
- 有两种创建形式,一种以Shape为父组件,一种是绘制组件单独使用
Shape() {
Rect().width(300).height(50)//以Shape作为父组件使用
}
Circle({ width: 150, height: 150 })//单独使用
- 绘制组件有七种类型:圆形(Circle)、椭圆形(Ellipse)、直线(Line)、拆线(Polyline)、多边形(Polygon)、路径(Path)、矩形(Rect)。
- 形状视口 viewPort
Shape() {
Rect({ width: 100, height: 100 }).fill(0xf7f7f7)
Circle({ width: 150, height: 150 }).fill(0x00c250)
}.viewPort({ x: 0, y: 0, width: 100, height: 100 })//根据这个视口与宽高比进行放大shape内的组件大小
.width(150)
.h