概要
鸿蒙Next Arkts 常用控件属性
Image 方法 (待更新)
Image($r('app.media.splash'))//图片资源位置
.width('100%')//图片宽度,可填百分比和数值
.height(100)//图片高度,同width可添百分比和数值
.aspectRatio(16 / 9) // 设置宽高比为16:9
.objectFit(ImageFit.Contain) //填充容器的方式 Contain:居中,
//Cover:铺满,超出部分剪切
//Auto:自适应显示器,这个和cover不一样,不会铺满,也会等比例,他会讲最短的边拉长,如果是长方形就把宽铺满,长自适应,
//Fill :铺满,边形,长宽都铺满
//ScaleDown : 保持显示宽高比,图像会缩小或保持不变。
Image加载网络图片
image加载网络图片时可直接加载,如
Image("http://****")
这种方式比较简便,但是可能会有以下问题
- 大图加载时无法提前下载,白块显示的时间较长;
- 小图设置同步加载,在弱网环境下,可能会阻塞UI线程造成冻屏问题;
- 在快速滑动的瀑布流中,无法提前对即将要显示的图片进行下载,导致滑动白块较多
加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。使用HTTP工具包发送网络请求,接着将返回的数据解码为Image组件中的PixelMap
例子如下
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
@Entry
@Component
struct ImageExample2 {
@State pixelMapImg: PixelMap | undefined = undefined;
aboutToAppear() {
this.requestImageUrl('https://www.example.com/xxx.png');// 请填写一个具体的网络图片地址
}
requestImageUrl(url: string) {
http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse)=> {
if (error) {
console.error(`request image failed: url: ${url}, code: ${error.code}, message: ${error.message}`);
} else {
let imgData: ArrayBuffer = data.result as ArrayBuffer;
console.info(`request image success, size: ${imgData.byteLength}`);
let imgSource: image.ImageSource = image.createImageSource(imgData);
class sizeTmp {
height: number = 100
width: number = 100
}
let options: Record<string, number | boolean | sizeTmp> = {
'alphaType': 0,
'editable': false,
'pixelFormat': 3,
'scaleMode': 1,
'size': { height: 100, width: 100 }
}
imgSource.createPixelMap(options).then((pixelMap: PixelMap) => {
console.error('image createPixelMap success');
this.pixelMapImg = pixelMap;
})
}
})
}
build() {
Column() {
Image(this.pixelMapImg)
.alt($r('app.media.img'))
.objectFit(ImageFit.None)
.width('100%')
.height('100%')
}
}
}
总结:就是将网络图片,通过http异步请求,将图片变为PixelMap,从而填充Image