目录

如何获取组件在屏幕中显示的比例

问题现象

检查组件在屏幕中是否被遮挡住显示不全,如何获取组件在屏幕中的显示比例?

效果预览

背景知识

解决方案

使用display.getAllDisplays获取到屏幕的宽高,再使用onAreaChange获取组件宽高,最后通过计算获得组件在屏幕中的显示比例。

代码示例如下:

import { display, UIContext } from '@kit.ArkUI';

@Entry
@Component
struct AreaExample {
  @State value: string = '举头望明月,低头思故乡。';
  @State screenWidth: number = 0;
  @State screenHeight: number = 0;
  @State Ratio: number = 0;
  uiContext: UIContext = new UIContext();

  aboutToAppear() {
    display.getAllDisplays((err, data) => {
      this.screenWidth = data[0].width;
      this.screenHeight = data[0].height;
    });
  }

  build() {
    Column() {
      Text(this.value)
        .padding(10)
        .backgroundColor('#ffd6d6d6')
        .fontSize(20)
        .onClick(() => {
          this.value = `${this.value}举头望明月,低头思故乡。`;
        })
        .onAreaChange((oldValue: Area, newValue: Area) => {
          let width = newValue.width as number;
          let height = newValue.height as number;
          this.Ratio =
            (this.uiContext.vp2px(width) * this.uiContext.vp2px(height)) / (this.screenWidth * this.screenHeight);
        });
      Text(`组件在屏幕中显示的比例:${'\n'} ${this.Ratio}`).margin({ right: 30, left: 30 });
    }
    .width('100%').height('100%');
  }
}