当前位置:首页 » 程序代码 » 正文

arkts 获取手机的宽高尺寸,并判断横竖屏状态

注意,以下代码用真机来测试,用DevEco Studio的预览器是得不到结果的。

代码如下

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

@Entry
@Component
struct Index {
  @State widthVp: number = 0
  @State heightVp: number = 0
  @State str1: string = '初始状态-代码来自 wb98.com'

  build() {
    Column({space:10}) {
      Button('确定')
        .onClick(() => {
          try {
            let displayInfo = display.getDefaultDisplaySync();
            let widthPx = displayInfo.width; // 屏幕宽度(像素单位)
            let heightPx = displayInfo.height; // 屏幕高度(像素单位)
            this.widthVp = px2vp(widthPx); // 转换为虚拟像素单位vp
            this.heightVp = px2vp(heightPx);

            if (this.widthVp < this.heightVp) {
              this.str1 = '竖屏'
            } else {
              this.str1 = '横屏'
            }
          } catch (error) {
            AlertDialog.show({
              message: '获取手机尺寸失败'
            })
          }
        })

      Text(this.widthVp.toString())
      Text(this.heightVp.toString())
      Text(this.str1)
    }
  }
}


打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/369.html

鸿蒙  arkts  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号