文档管理中心
最佳实践应用框架窗口与屏幕管理PC/2in1异形窗口

PC/2in1异形窗口

概述

一般情况下,UI开发都是在矩形窗口上操作,但在PC/2in1设备上,应用还可以使用各类异形窗口来展现交互内容。这里的异形是指除默认矩形以外的形状,包括但不限于圆形、三角形以及其他不规则的形状等。开发者通过使用这些异形形状的窗口,结合窗口中的内容展示UI交互的多样性,一定程度上能够提升应用体验。类似的示例有:文字应用中的放大镜、带指示箭头的气泡框、提供辅助功能的悬浮窗等。

本文主要介绍在PC/2in1设备上实现异形窗口。根据窗口的形状类别,可分为以下场景:

实现原理

在创建窗口时,ArkUI以宽、高为参数描绘窗口初始大小,其形状默认为矩形,可以通过设置掩码改变窗口最终呈现的形状。

该掩码是一个二维数组,其大小对应初始窗口的宽和高,所以可以把该数组中的元素与窗口中的像素一一对应起来;数组中的每一项值只能是0或1,其中数字0表示窗口对应位置的像素是透明的,数字1代表对应像素不透明。

简单来说,掩码即是由数字1描绘的窗口形状点阵图。具体使用可参考setWindowMask()接口。

开发流程

  1. 创建异形子窗口或悬浮窗,设置窗口的位置、大小等属性,设置窗口加载的page页面。
  2. 根据待实现的异形形状,计算出与其对应的二维数组掩码,对目标窗口设置该掩码。
  3. 根据逻辑需要,显示目标异形窗口。
说明

掩码windowMask二维数组的大小需要与窗口初始宽、高一致,且每项值只能是0或1,否则设置的形状不会生效。

图形形状窗口

场景案例

待开发的异形窗口,其形状是具有一定规则的几何图形,通过描述语言能得到精确且唯一的形状。本节以下面两种形状的实现为例进行说明:直径为500的圆形;底500、高500的等腰三角形。

创建子窗口

在得到异形窗口前,需要先创建一个默认的矩形窗口,开发步骤如下:

  1. 为使用setWindowMask()等接口,需要额外配置syscap.json文件,在模块/src/main目录下,创建syscap.json文件,填入以下内容:

    收起
    自动换行
    深色代码主题
    复制
    1. // entry/src/main/syscap.json
    2. {
    3. "devices": {
    4. "general": [
    5. "2in1"
    6. ]
    7. },
    8. "development": {
    9. "addedSysCaps": [
    10. "SystemCapability.Window.SessionManager"
    11. ]
    12. }
    13. }

  2. 具体代码中,使用createSubWindow()创建子窗口(参考设置应用子窗口),或使用createWindow()接口创建悬浮窗,设置窗口的位置、大小及其他属性等,然后使用setUIContent()接口设置窗口加载的page页面。

    收起
    自动换行
    深色代码主题
    复制
    1. windowStage = AppStorage.get('windowStage');
    2. if (windowStage === null) {
    3. hilog.error(0x0000, 'Sample', 'Failed to create the subwindow. Cause: windowStage is null');
    4. return;
    5. }
    6. const windowWidth = 500;
    7. const windowHeight = 500;
    8. try {
    9. subWindow = await windowStage!.createSubWindow('mySubWindow');
    10. subWindow.moveWindowTo(300, 300);
    11. subWindow.resize(windowWidth, windowHeight);
    12. subWindow.setUIContent('pages/SubPage');
    13. // ...
    14. subWindow.showWindow();
    15. } catch (exception) {
    16. hilog.error(0x0000, 'Sample', 'Failed to create sub window. Cause: ' + JSON.stringify(exception));
    17. }

设置窗口形状

  1. 根据要实现的异形窗口形状,计算二维数组掩码windowMask。

    • 以下是以原矩形中点为圆心、直径为500的圆。最终效果见圆形子窗口效果。
      收起
      自动换行
      深色代码主题
      复制
      1. function fillCircle(array: number[][], x: number, y: number, radius: number): void {
      2. for (let i = x - radius; i <= x + radius; i++) {
      3. for (let j = y - radius; j <= y + radius; j++) {
      4. const distSquared = (i - x)**2 + (j - y)**2;
      5. if (distSquared <= radius**2 && i >= 0 && j >= 0 && i < array.length && j < array[0].length) {
      6. array[i][j] = 1;
      7. }
      8. }
      9. }
      10. }
      11. async function getCircleMask(width: number, height: number): Promise<number[][]> {
      12. const radius = Math.min(width, height) / 2;
      13. const maskArray: number[][] = new Array(height).fill(null).map(() => new Array(width).fill(0));
      14. fillCircle(maskArray, height / 2, width / 2, radius);
      15. return maskArray;
      16. }
    • 以下以原矩形宽为底边、原矩形高为高的等腰三角形。最终效果见三角形子窗口效果。
      收起
      自动换行
      深色代码主题
      复制
      1. function fillTriangle(array: number[][], base: number, height: number): void {
      2. // i < height-10 in order to remove the round corner
      3. for (let i = 0; i < height - 10; i++) {
      4. for (let j = 0; j < base; j++) {
      5. if (j >= base / 2 - base / 2 * i / height && j <= base / 2 + base / 2 * i / height) {
      6. array[i][j] = 1;
      7. }
      8. }
      9. }
      10. }
      11. async function getTriangleMask(width: number, height: number): Promise<number[][]> {
      12. const maskArray: number[][] = new Array(height).fill(null).map(() => new Array(width).fill(0));
      13. fillTriangle(maskArray, width, height);
      14. return maskArray;
      15. }

  2. 使用setWindowMask(windowMask)接口,设置窗口形状。

    收起
    自动换行
    深色代码主题
    复制
    1. async function setWindowShape(win: window.Window, width: number,
    2. height: number, getMaskFunc: (w: number, h: number, picPath?: string) => Promise<number[][]>,
    3. picPath?: string): Promise<void> {
    4. const windowMask = await getMaskFunc(width, height, picPath);
    5. if (canIUse('SystemCapability.Window.SessionManager')) {
    6. try {
    7. win.setWindowMask(windowMask);
    8. } catch (e) {
    9. let err = e as BusinessError;
    10. hilog.error(0x0000, 'Simple', `failed code=${err.code}, message=${err.message}`);
    11. }
    12. } else {
    13. hilog.info(0x0000, 'Simple', 'can not use SessionManager syscap');
    14. }
    15. }
    16. /**
    17. * Set the window with circle shape
    18. * @param win The target window
    19. * @param width The original window width
    20. * @param height The original window height
    21. */
    22. export async function setWindowCircleShape(win: window.Window, width: number,
    23. height: number): Promise<void> {
    24. setWindowShape(win, width, height, getCircleMask)
    25. }
    26. /**
    27. * Set the window with triangle shape
    28. * @param win The target window
    29. * @param width The original window width
    30. * @param height The original window height
    31. */
    32. export async function setWindowTriangleShape(win: window.Window, width: number,
    33. height: number): Promise<void> {
    34. setWindowShape(win, width, height, getTriangleMask)
    35. }

  3. 使用showWindow()接口显示异形子窗口。

    收起
    自动换行
    深色代码主题
    复制
    1. subWindow.showWindow();

实现效果

图1 圆形子窗口效果
图2 三角形子窗口效果

不规则形状窗口

场景案例

待开发的异形窗口,呈现出不规则的形状。这种情况通常先由设计人员提供图形文件,开发人员以文件为输入,基于ArkUI提供的图片处理能力,转化为相应的形状掩码,最后实现不规则的窗口形状。

图3 不规则示例图

本节以上图为例说明不规则形状窗口的实现过程。

开发步骤

首先同样需要先创建子窗口,然后再依以下步骤开发。

  1. 读取图片文件,将其转化为pixelMap数据。

    收起
    自动换行
    深色代码主题
    复制
    1. /**
    2. * Convert image to PixelMap object
    3. */
    4. export async function image2PixelMap(Context: Context, icon: string, w: number, h: number): Promise<image.PixelMap> {
    5. try {
    6. const rawFileDescriptor: resourceManager.RawFileDescriptor = Context.resourceManager.getRawFdSync(icon);
    7. const imageSource: image.ImageSource = image.createImageSource(rawFileDescriptor);
    8. const pixelMap: Promise<PixelMap> = imageSource.createPixelMap({
    9. editable: false,
    10. desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
    11. desiredSize: { width: w, height: h }
    12. });
    13. imageSource.release()
    14. return pixelMap;
    15. } catch (e) {
    16. let err = e as BusinessError;
    17. hilog.error(0x0000, 'Simple', `failed code=${err.code}, message=${err.message}`);
    18. }
    19. return new Promise<image.PixelMap>((resolve, reject) => {
    20. reject('null')
    21. });
    22. }

  2. 从pixelMap数据中取出颜色信息数组,将每个像素的透明度单独提取至allPixels,再转化生成为对应形状的二维数组掩码maskArray。

    收起
    自动换行
    深色代码主题
    复制
    1. export async function getPicMask(Context: Context,width: number, height: number, picPath: string): Promise<number[][]> {
    2. const maskArray: number[][] = new Array(height).fill(null).map(() => new Array(width).fill(0));
    3. const pixelMap: image.PixelMap = await image2PixelMap(Context, picPath, width, height);
    4. const pixelArrayBuffer: ArrayBuffer = new ArrayBuffer(width * height * 4);
    5. await pixelMap.readPixelsToBuffer(pixelArrayBuffer);
    6. const allPixels: number[] = [];
    7. const unit8Pixels: Uint8Array = new Uint8Array(pixelArrayBuffer);
    8. for (let i = 0, j = 0; i < unit8Pixels.length; i += 4, j++) {
    9. // unit8Pixels[i+3] is alpha channel of BGRA_8888
    10. allPixels[j] = unit8Pixels[i + 3] > 0 ? 1 : 0;
    11. }
    12. pixelMap.release()
    13. let k = 0;
    14. for (let i = 0; i < height; i++) {
    15. for (let j = 0; j < width; j++) {
    16. maskArray[i][j] = allPixels[k++];
    17. }
    18. }
    19. return maskArray;
    20. }

  3. 使用setWindowMask(windowMask)接口,设置窗口形状。

    收起
    自动换行
    深色代码主题
    复制
    1. async function setWindowShape(win: window.Window, width: number,
    2. height: number, getMaskFunc: (w: number, h: number, picPath?: string) => Promise<number[][]>,
    3. picPath?: string): Promise<void> {
    4. const windowMask = await getMaskFunc(width, height, picPath);
    5. if (canIUse('SystemCapability.Window.SessionManager')) {
    6. try {
    7. win.setWindowMask(windowMask);
    8. } catch (e) {
    9. let err = e as BusinessError;
    10. hilog.error(0x0000, 'Simple', `failed code=${err.code}, message=${err.message}`);
    11. }
    12. } else {
    13. hilog.info(0x0000, 'Simple', 'can not use SessionManager syscap');
    14. }
    15. }
    16. /**
    17. * Set the window with pic shape
    18. * @param win The target window
    19. * @param width The original window width
    20. * @param height The original window height
    21. * @param picPath The pic path in rawfile
    22. */
    23. export async function setWindowPicShape(win: window.Window, Context: Context, width: number,
    24. height: number, picPath: string): Promise<void> {
    25. setWindowShape(win, width, height, (w, h, picPath) => {
    26. return getPicMask(Context,w, h, picPath!)
    27. }, picPath)
    28. }

  4. 使用showWindow()接口显示异形子窗口。

    收起
    自动换行
    深色代码主题
    复制
    1. subWindow.showWindow();

实现效果

图4 不规则形状子窗口效果

示例代码

在 最佳实践 中进行搜索
请输入您想要搜索的关键词