Canvas画布组件在平板横屏显示时,绘制起点未动态变化,导致画布内容底部被其他组件遮挡。
@Entry
@Component
struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.context.fillStyle = '#D1D1D6';
// 坐标都是固定值,容易造成布局异常
this.context.fillRect(200, 200, 100, 100);
});
}
.width('100%')
.height('100%');
}
} 使用display.getDefaultDisplaySync()获取屏幕当前尺寸,根据屏幕尺寸及绘制的图形尺寸动态计算绘制起点坐标。
import { display } from '@kit.ArkUI';
@Entry
@Component
struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
@State deviceWidth: number = 0;
@State deviceHeight: number = 0;
aboutToAppear(): void {
// 获取屏幕宽高
this.deviceWidth = this.getUIContext().px2vp(display.getDefaultDisplaySync().width);
this.deviceHeight = this.getUIContext().px2vp(display.getDefaultDisplaySync().height);
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
.onReady(() => {
this.context.fillStyle = '#D1D1D6';
this.context.fillRect(this.deviceWidth * 0.5 - 50, this.deviceHeight * 0.5 - 100, 100, 100);
});
}
.width('100%')
.height('100%');
}
}