在鸿蒙星河版开发中调整屏幕亮度
setWindowBrightness可以用于设置屏幕亮度,屏幕亮度值,值为0-1之间。1表示最亮。
在EntryAbility.ets中的onWindowStageCreate方法中将WindowStage设置一个AppStorage,参考代码如下:
AppStorage.setOrCreate('windowStage',windowStage);
// EntryAblilty
onWindowStageCreate(windowStage: window.WindowStage): void {
AppStorage.setOrCreate('windowStage',windowStage);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
通过setWindowBrightness可以设置屏幕亮度
## import { window } from '@kit.ArkUI'
@Entry
@Component
struct SettingScreenBrightness {
windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage;
// 获取主窗口的方式
mainWin: window.Window = this.windowStage.getMainWindowSync();
// 进入页面
aboutToAppear(): void {
// 修改brightness即可改变屏幕亮度
let brightness = 1;
this.windowStage = AppStorage.get('windowStage') as window.WindowStage;
// 获取主窗口的方式
this.mainWin = this.windowStage.getMainWindowSync();
// 获取最上层窗口的方式
window.getLastWindow(getContext(this));
try {
this.mainWin.setWindowBrightness(brightness, (err) => {
if (err.code) {
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the brightness.');
});
} catch (exception) {
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception));
}
}
// 离开页面
aboutToDisappear(): void {
// 修改brightness即可改变屏幕亮度
let brightness = -1
this.windowStage = AppStorage.get('windowStage') as window.WindowStage;
// 获取主窗口的方式
this.mainWin = this.windowStage.getMainWindowSync();
// 获取最上层窗口的方式
window.getLastWindow(getContext(this));
try {
this.mainWin.setWindowBrightness(brightness, (err) => {
if (err.code) {
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the brightness.');
});
} catch (exception) {
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception));
}
}
build() {
Row() {
Column({ space: 10 }) {
Text('屏幕亮度设置demo')
.fontSize(25)
.margin(20)
.fontColor(0x3399FF)
}.width('100%')
}.height('100%').backgroundColor(Color.White)
}
}
setWindowBrightness 官网传送门
setWindowBrightness(brightness: number, callback: AsyncCallback): void
允许应用主窗口设置屏幕亮度值,使用callback异步回调。
当前屏幕亮度规格:窗口设置屏幕亮度生效时,控制中心不可以调整系统屏幕亮度,窗口恢复默认系统亮度之后,控制中心可以调整系统屏幕亮度。
参数
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。 |
callback | AsyncCallback | 是 | 回调函数。 |