问题现象
新建工程,通过ImageBitmap或其他组件使用src/main/ets目录中的本地图片无法加载。
可能原因
若使用DevEco Studio 6.0.0 Beta2及之后的版本创建的新工程,会默认不打包模块src/main目录中的图片资源,具体参考copyCodeResource
解决措施
// xxx.ets
@Entry
@Component
struct VideoPlayer {
private controller: VideoController = new VideoController()
private previewUris: Resource = $r('app.media.preview')
private innerResource: Resource = $rawfile('videoTest.mp4')
build() {
Column() {
Video({
src: this.innerResource,
previewUri: this.previewUris,
controller: this.controller
})
.onUpdate((event) => { // Triggered when the playback progress changes.
console.info("Video update.");
})
.onPrepared((event) => { // Triggered when video preparation is complete.
console.info("Video prepared.");
})
.onError(() => { // Triggered when the video playback fails.
console.error("Video error.");
})
.onStop(() => { // Triggered when the video playback stops.
console.info("Video stopped.");
})
}
}
} // xxx.ets
@Entry
@Component
struct ImageExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
// Replace "common/images/example.jpg" with the image resource file you use.
// private img: ImageBitmap = new ImageBitmap("common/images/example.jpg"); // This relative path writing will make it impossible to record pictures in the new template
private img: ImageBitmap = new ImageBitmap(this.getUIContext().getHostContext()?.resourceManager
.getDrawableDescriptorByName("example")
.getPixelMap()); // You can refer to the interface for using resourceManager
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.context.drawImage(this.img, 0, 0, 500, 500, 0, 0, 400, 200)
this.img.close()
})
}
.width('100%')
.height('100%')
}
}