获取鸿蒙手机屏幕的宽高

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

获取鸿蒙手机屏幕的宽高

DeviceUtil.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

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

export class DeviceUtil {
private static width = 0;
private static widthPx = 0;
private static height = 0;
private static heightPx = 0;

public static getDisplayWidth(): number {
if (DeviceUtil.width == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.width;
}

public static getDisplayWidthPx(): number {
if (DeviceUtil.widthPx == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.widthPx;
}

public static getDisplayHeight(): number {
if (DeviceUtil.height == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.height;
}

public static getDisplayHeightPx(): number {
if (DeviceUtil.heightPx == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.heightPx;
}

private static setupDisplaySize() {
let width = display.getDefaultDisplaySync().width;
let height = display.getDefaultDisplaySync().height;
DeviceUtil.widthPx = width;
DeviceUtil.width = px2vp(width);
DeviceUtil.heightPx = height;
DeviceUtil.height = px2vp(height);
}
}

参考

https://segmentfault.com/q/1010000044715976

作者

Dench

发布于

2024-05-09

更新于

2024-05-09

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×