鸿蒙:获取屏幕的刷新率、分辨率、监听截屏或录屏状态等
1、前言
在日常开发过程中,我们有时需要获取用户设备的屏幕信息,便于我们调整不同设备下的UI布局的宽高。我们也可通过display接口监听用户在使用过程中是否截图或录屏。
2、参考文档
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-displayhttps://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-display
3、核心思路
根据鸿蒙官方api——display的一些属性来监听设备的屏幕信息或状态。
4、运行效果
5、完整代码
Index.ets
import {display
} from '@kit.ArkUI';@Entry
@ComponentV2
struct Index {@Local value: string = "";display: display.Display | null = null;aboutToAppear(): void {try {this.display = display.getDefaultDisplaySync();} catch (exception) {console.error(`Failed to get default display. Code: ${exception.code}, message: ${exception.message}`);}let callback2: Callback<boolean> = (captureStatus: boolean) => {// 开始截屏或录屏if (captureStatus) {this.value = "截屏或录屏";} else {this.value = "录屏结束";}// captureStatus为true表示显示设备开始截屏、投屏或录屏,false表示结束截屏、投屏或录屏console.info('Listening capture status: ' + captureStatus);};// 开启屏幕截屏、投屏、录屏状态变化的监听display.on('captureStatusChange', callback2);}build() {Column({ space: 20 }) {// 获取屏幕的idText("屏幕Id:" + this.display?.id).fontSize(20).fontWeight(FontWeight.Bold)// 获取屏幕的刷新率Text("屏幕的刷新率:" + this.display?.refreshRate + "Hz").fontSize(20).fontWeight(FontWeight.Bold)// 获取屏幕的分辨率Text("获取屏幕的分辨率:" + this.display?.width + "x" + this.display?.height).fontSize(20).fontWeight(FontWeight.Bold)Text("截屏或录屏状态监听:" + this.value).fontSize(20).fontWeight(FontWeight.Bold)}.justifyContent(FlexAlign.Center).width("100%").height("100%")}
}
觉得有帮助可以点赞或收藏