智能客服
你问我答,随时在线为你解决问题
在使用Image组件时,如何实现以下场景:
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
@Entry
@Component
struct Index {
@State pixelMap: PixelMap | undefined = undefined;
context: Context = this.getUIContext().getHostContext() as Context;
path: string = this.context.filesDir + '/hehe.jpg';
decodingOptions: image.DecodingOptions = {
editable: true,
desiredPixelFormat: 3,
};
async aboutToAppear(): Promise<void> {
let resourceManager = this.context.resourceManager;
let imageArray =
await resourceManager.getMediaContent($r('app.media.BigImage').id); // 需开发者自行更换图片
let file = fs.openSync(this.path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
fs.writeSync(file.fd, imageArray.buffer);
} catch (err) {
} finally {
fs.closeSync(file);
}
}
async packingDetail(targetWidth: number, targetHeight: number) {
if (this.pixelMap) {
let imageInfo = await this.pixelMap.getImageInfo();
// 计算压缩比
let scaleX: number = targetWidth / imageInfo.size.width;
let scaleY: number = targetHeight / imageInfo.size.height;
this.pixelMap.scaleSync(scaleX, scaleY);
}
}
build() {
Row() {
Column() {
Image(this.pixelMap)
.width(200)
.height(200)
.backgroundColor(Color.Gray)
.margin({ bottom: 40 })
.objectFit(ImageFit.Contain)
Button('1:3').onClick(async () => {
const imageSource: image.ImageSource = image.createImageSource(this.path);
// 创建pixelMap
this.pixelMap = await imageSource.createPixelMap(this.decodingOptions);
// 指定压缩宽、高
this.packingDetail(100, 300);
}).margin({ bottom: 20 })
Button('1:2').onClick(async () => {
// path为已获得的沙箱路径
const imageSource: image.ImageSource = image.createImageSource(this.path);
// 创建pixelMap
this.pixelMap = await imageSource.createPixelMap(this.decodingOptions);
// 指定压缩宽、高
this.packingDetail(100, 200);
})
}
.width('100%')
}
.height('100%')
}
} Q:ImageAnimator在设置了fixedSize之后,图片不会跟随组件宽高做拉伸。
A:设置fixedSize属性后,ImageAnimator将维持图片的原始宽高比。当图片原始尺寸与组件尺寸不一致时,图片会适配至ImageAnimator的宽高范围内显示,而不会被拉伸变形。