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 源码


作者:ITmob
来源:ITmob.cn
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×