拖拽到小艺后显示不支持处理此类数据是因为小艺不支持读取资源文件的uri,需要将资源文件的图片转换成PixelMap后,用PixelMap数据初始化图片。代码如下:
/*
*
* Copyright (c) 2025 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { common } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
@Entry
@Component
struct Index {
@State imageUrl: Resource | string | PixelMap = $rawfile('shineImage.png');
context = this.getUIContext().getHostContext() as common.UIAbilityContext;
fileName: string = 'shineImage.png';
build() {
RelativeContainer() {
Column() {
Image(this.imageUrl)
.width(`200vp`)
.height(`300vp`)
.margin({ bottom: 50 })
Button('转换成PixelMap初始化图片').onClick(() => {
this.ChangeImageFromPixelMap();
}).borderRadius(5)
.backgroundColor(Color.Brown)
}
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
}
ChangeImageFromPixelMap(): void {
try {
this.context.resourceManager.getRawFileContent(this.fileName, (err, data) => {
if (err) {
console.log(`get RawFile error:${JSON.stringify(err)}`);
return;
}
let ops: image.SourceOptions = {
sourceDensity: 98,
};
let imageSource: image.ImageSource = image.createImageSource(data.buffer as ArrayBuffer, ops);
imageSource.createPixelMap().then((commodityPixelMap) => {
this.imageUrl = commodityPixelMap;
});
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`copy directory failed with error message: ${JSON.stringify(err)}`);
}
}
} 需要将下图另存为shineImage.png。并且复制到工程的rawfile目录下。
