C01406/com.example/OHOS::RS com.example I RSCanvasDrawingNode::ResetSurface id:271995983888411 width:2760 height:1256 C01406/com.example/OHOS::RS com.example I RSCanvasDrawingNode::ResetSurface id:271995983888411 width:1256 height:2760
恢复画布样例如下。
import common from '@ohos.app.ability.common';
import window from '@ohos.window';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private imageData?: ImageData = undefined;
private canvasWidth: number = 0;
private canvasHeight: number = 0;
aboutToAppear(): void {
// 设置屏幕自动旋转
(this.getUIContext().getHostContext() as common.UIAbilityContext).windowStage.getMainWindow().then((win) => {
win.setPreferredOrientation(window.Orientation.AUTO_ROTATION).then(() => {
console.info('Succeeded in setting the window orientation.');
}).catch((err: BusinessError) => {
console.error(`Failed to set the window orientation. Cause code: ${err.code}, message: ${err.message}`);
});
}).catch((err: BusinessError) => {
console.error(`Failed to get the main window. Cause code: ${err.code}, message: ${err.message}`);
});
}
aboutToDisappear(): void {
// 设置屏幕竖屏
(this.getUIContext().getHostContext() as common.UIAbilityContext).windowStage.getMainWindow().then((win) => {
win.setPreferredOrientation(window.Orientation.PORTRAIT).then(() => {
console.info('Succeeded in setting the window orientation.');
}).catch((err: BusinessError) => {
console.error(`Failed to set the window orientation. Cause code: ${err.code}, message: ${err.message}`);
});
}).catch((err: BusinessError) => {
console.error(`Failed to get the main window. Cause code: ${err.code}, message: ${err.message}`);
});
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#f1f3f5')
.onReady(() => {
this.canvasWidth = this.context.width;
this.canvasHeight = this.context.height;
// 恢复画布
if (this.imageData) {
this.context.putImageData(this.imageData, 0, 0);
}
})
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.context.moveTo(event.touches[0].displayX, event.touches[0].displayY);
}
if (event.type === TouchType.Move) {
this.context.lineTo(event.touches[0].displayX, event.touches[0].displayY);
this.context.stroke();
}
// 当手指抬起时,保存画布内容
if (event.type === TouchType.Up) {
this.imageData = this.context.getImageData(0, 0, this.canvasWidth, this.canvasHeight);
}
})
}
.width('100%')
.height('100%')
}
}