HarmonyOS鸿蒙Next中app切后台需要模糊页面,怎么实现
HarmonyOS鸿蒙Next中app切后台需要模糊页面,怎么实现 我看过论坛里面的帖子,做法都是设置某个页面的背景,我的需求是在任意页面,实现高斯模糊,不强依赖某个页面,应该怎么做
3 回复
onPageShow() {
let context = getContext(this) as common.UIAbilityContext;
let windowStage = context.windowStage;
windowStage.on("windowStageEvent", (data) => {
if (data === window.WindowStageEventType.PAUSED) {
this.flag = true
} else {
this.flag = false
}
})
}
build() {
Row() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
.foregroundBlurStyle(this.flag ? BlurStyle.Thin : BlurStyle.NONE, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT
})
}
使用foregroundBlurStyle调整BlurStyle和ForegroundBlurStyleOptions,参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-foreground-blur-style-V5#foregroundblurstyle,需要在所有@Entry组件中设置模糊,实现任意页面切后台时都能模糊。
更多关于HarmonyOS鸿蒙Next中app切后台需要模糊页面,怎么实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,当应用程序切换到后台时,可以通过设置WindowManager.LayoutParams.FLAG_BLUR_BEHIND标志来模糊页面。具体实现步骤如下:
- 在
Ability或AbilitySlice中获取当前窗口的Window对象。 - 使用
WindowManager.LayoutParams设置FLAG_BLUR_BEHIND标志。 - 调用
Window的setAttributes方法应用设置。
示例代码如下:
import window from '@ohos.window';
// 获取当前窗口
window.getTopWindow((err, topWindow) => {
if (err) {
console.error('Failed to get the top window. Cause: ' + JSON.stringify(err));
return;
}
// 获取窗口属性
let layoutParams = topWindow.getWindowProperties();
// 设置模糊背景标志
layoutParams.flags |= window.WindowManager.LayoutParam.FLAG_BLUR_BEHIND;
// 应用窗口属性
topWindow.setWindowProperties(layoutParams, (err) => {
if (err) {
console.error('Failed to set window properties. Cause: ' + JSON.stringify(err));
return;
}
});
});
在HarmonyOS鸿蒙Next中,当应用切换到后台时,可以通过监听onWindowFocusChange事件来实现页面模糊效果。具体步骤如下:
- Override
onWindowFocusChange方法:在Ability或AbilitySlice中重写该方法,判断应用是否失去焦点。 - 应用模糊效果:当应用失去焦点时,通过设置
Component的BlurStyle或使用BlurEffect来实现模糊效果。 - 恢复原状:当应用重新获得焦点时,移除模糊效果。
示例代码:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
// 应用模糊效果
component.setBackground(new BlurEffect(BlurStyle.THIN));
} else {
// 移除模糊效果
component.setBackground(null);
}
}
通过这种方式,可以在应用切后台时实现页面模糊效果,提升用户体验。

