1# 如何实现横竖屏切换
2
3## 场景说明
4横竖屏切换是音视频应用常用的功能,OpenHarmony也提供了相应的能力,可以方便的实现横竖屏切换,本文即为大家介绍如何完成横竖屏切换。
5
6## 效果呈现
7本例效果如下:
8- 点击窗口中间的“横竖屏切换”按钮可以实现横竖屏之间的切换。
9- 初次点击由竖屏切换为横屏,再次点击由横屏切换为竖屏。
10
11![horizontal-vertical-switch](figures/horizontal-vertical-switch.gif)
12
13## 环境要求
14
15本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发:
16
17- IDE: DevEco Studio 4.0 Release
18- SDK: Ohos_sdk_public 4.0.10.13 (API Version 10 Release)
19
20
21## 实现思路
22通过window模块的getLastWindow接口获取到当前窗口,然后使用窗口的setPreferredOrientation接口实现横竖屏的切换,参数为window.Orientation.PORTRAIT时切换为竖屏,参数为window.Orientation.LANDSCAPE时切换为横屏。
23
24## 开发步骤
25开发步骤仅呈现关键代码,全量代码请参考完整代码章节。
261. 搭建UI框架,添加“横竖屏切换”按钮。
27    ```ts
28    Column(){
29      Button("横竖屏切换")
30        .onClick(()=>{
31
32        })
33    }
34    .width('100%')
35    .height('100%')
36    .justifyContent(FlexAlign.Center)
37    ```
382. 实现横竖屏切换接口horVerSwitch。
39    ```ts
40    horVerSwitch(){
41      let context = getContext(this) as common.UIAbilityContext;
42      // 使用getLastWindow获取当前窗口
43      window.getLastWindow(context).then((lastWindow)=>{
44        // 使用setPreferredOrientation实现横竖屏切换
45        lastWindow.setPreferredOrientation(this.isFullScreen ? window.Orientation.PORTRAIT : window.Orientation.LANDSCAPE)
46        this.isFullScreen = !this.isFullScreen
47      })
48    }
49    ```
503. 给“横竖屏切换”按钮添加点击事件并绑定horVerSwitch,从而实现点击按钮,完成横竖屏切换。
51    ```ts
52    Column(){
53      Button("横竖屏切换")
54        .onClick(()=>{
55          // 绑定horVerSwitch
56          this.horVerSwitch()
57        })
58    }
59    .width('100%')
60    .height('100%')
61    .justifyContent(FlexAlign.Center)
62    ```
63
64## 完整代码
65本例完整代码如下:
66
67```ts
68// xxx.ets
69import window from '@ohos.window';
70import common from '@ohos.app.ability.common';
71
72@Entry
73@Component
74struct HorVerSwitch{
75  @State isFullScreen:boolean = false
76
77  // 横竖屏切换
78  horVerSwitch(){
79    let context = getContext(this) as common.UIAbilityContext;
80    // 使用getLastWindow获取当前窗口
81    window.getLastWindow(context).then((lastWindow)=>{
82      // 使用setPreferredOrientation实现横竖屏切换
83      lastWindow.setPreferredOrientation(this.isFullScreen ? window.Orientation.PORTRAIT : window.Orientation.LANDSCAPE)
84      this.isFullScreen = !this.isFullScreen
85    })
86  }
87
88  build(){
89    Column(){
90      Button("横竖屏切换")
91        .onClick(()=>{
92          this.horVerSwitch()
93        })
94    }
95    .width('100%')
96    .height('100%')
97    .justifyContent(FlexAlign.Center)
98  }
99}
100```
101## 参考
102- [获取当前窗口(getLastWindow)](../application-dev/reference/apis-arkui/js-apis-window.md)
103- [横竖屏切换(setPreferredOrientation)](../application-dev/reference/apis-arkui/js-apis-window.md)
104
105