【HarmonyOS NEXT】web组件如何实现应用内全屏、以及横竖屏的自适应

【关键字】

应用内全屏 / 竖屏 / 横屏 / 自适应 / Web组件

【问题描述】

Web组件如何实现应用内全屏、以及横竖屏的自适应

【解决方案】

当前在Web里暂时不支持使用JS或CSS来实现横屏,需要ArkUI的媒体查询接口实现横屏,可以在Web的onFullScreenEnter和onFullScreenExit回调中监听是否点击全屏的按键,在这两个回调里使用媒体查询接口实现视频横向和竖向。

参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-layout-development-media-query-0000001774279802

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-web-0000001774281246#ZH-CN_TOPIC_0000001774281246__onfullscreenenter9

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-web-0000001774281246#ZH-CN_TOPIC_0000001774281246__onfullscreenexit9

当网页视频横向后需要在H5中设置横向宽高来适配使页面全屏,媒体查询接口只是让手机横屏。请参考如下代码:

import web_webview from '@ohos.web.webview'
import mediaquery from '@ohos.mediaquery';
import window from '@ohos.window';
import common from '@ohos.app.ability.common';

@Entry
@Component
struct MediaQueryExample {
@State color: string = '#DB7093';
@State text: string = 'Portrait';
@State portraitFunc:mediaquery.MediaQueryResult|void|null = null;
handler: FullScreenExitHandler | null = null
// 当设备横屏时条件成立
listener:mediaquery.MediaQueryListener = mediaquery.matchMediaSync('(orientation: landscape)');
controller: web_webview.WebviewController = new web_webview.WebviewController()
onPortrait(mediaQueryResult:mediaquery.MediaQueryResult) {
if (mediaQueryResult.matches as boolean) { // 若设备为横屏状态,更改相应的页面布局
this.color = '#FFD700';
this.text = 'Landscape';
} else {
this.color = '#DB7093';
this.text = 'Portrait';
}
}

aboutToAppear() {
// 绑定当前应用实例
// 绑定回调函数
this.listener.on('change', (mediaQueryResult:mediaquery.MediaQueryResult) => { this.onPortrait(mediaQueryResult) });
}

// 改变设备横竖屏状态函数
private changeOrientation(isLandscape: boolean) {
// 获取UIAbility实例的上下文信息
let context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 调用该接口手动改变设备横竖屏状态
window.getLastWindow(context).then((lastWindow) => {
lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT)
});
}

build() {
Column() {
Web({ src: $rawfile('video.html'), controller: this.controller })
.javaScriptAccess(true)
.domStorageAccess(true)
.onFullScreenEnter((event) => {
console.log("onFullScreenEnter...")
this.handler = event.handler
this.changeOrientation(true);
})
.onFullScreenExit(() => {
console.log("onFullScreenExit...")
if (this.handler) {
this.handler.exitFullScreen()
this.changeOrientation(false);
}
})
}
.width('100%').height('100%')
}
}

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值