ITmob-Ly
发布于 2022-04-12 / 1303 阅读
0

Compose Desktop创建带有自定义TitleBar可拖动的窗口

draggable_area.gif

Compose desktop的创建的窗口默认的TitleBar不可以自定义,所以可以使用WindowDraggableArea 创建允许使用鼠标拖动的窗口实现自定义的TitleBar。

设置窗口为未装饰 undecorated,移除默认的TitleBar,并且为其添加自定义可拖动标题栏(或使整个窗口可拖动)

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

fun main() = application {
    Window(onCloseRequest = ::exitApplication, undecorated = true) {
        WindowDraggableArea {
            Box(Modifier.fillMaxWidth().height(48.dp).background(Color.DarkGray))
        }
    }
}

请注意,WindowDraggableArea 只能在 singleWindowApplicatiowWindowDialog 内部使用。如果需要在另一个 Composable 函数中使用它,请将 WindowScope 作为接收器传递:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowScope
import androidx.compose.ui.window.application

fun main() = application {
    Window(onCloseRequest = ::exitApplication, undecorated = true) {
        AppWindowTitleBar()
    }
}

@Composable
private fun WindowScope.AppWindowTitleBar() = WindowDraggableArea {
    Box(Modifier.fillMaxWidth().height(48.dp).background(Color.DarkGray))
}

WindowDraggableArea source code: WindowDraggableArea 源码