You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose Desktop如何获取显示器的宽高?

在Jetpack Compose Desktop中获取显示器尺寸并实现自适应字体大小

1. 获取显示器宽高

Compose Desktop没有Android端的LocalConfiguration,但可以通过AWT的API直接获取屏幕信息,或者结合Compose的Window组件获取当前窗口所在屏幕的尺寸:

方式一:获取主屏幕尺寸

直接调用AWT的GraphicsEnvironment获取主屏幕的分辨率:

import java.awt.GraphicsEnvironment

fun getPrimaryScreenSize(): Pair<Int, Int> {
    val screen = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice.defaultConfiguration
    return screen.bounds.width to screen.bounds.height
}

方式二:获取当前窗口所在屏幕尺寸

如果应用窗口可能在多显示器环境下,推荐通过Compose的Window实例获取当前屏幕:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import java.awt.Window

fun main() = application {
    val screenWidth = remember { mutableStateOf(0) }
    val screenHeight = remember { mutableStateOf(0) }

    Window(onCloseRequest = ::exitApplication) {
        // 获取当前窗口对应的AWT Window对象
        val awtWindow = this.window
        LaunchedEffect(awtWindow) {
            val screen = awtWindow.graphicsConfiguration
            screenWidth.value = screen.bounds.width
            screenHeight.value = screen.bounds.height
        }

        Box(modifier = fillMaxSize(), contentAlignment = Alignment.Center) {
            Text(
                text = "屏幕尺寸:${screenWidth.value}x${screenHeight.value}",
                fontSize = calculateRelativeFontSize(screenWidth.value)
            )
        }
    }
}

2. 实现自适应字体大小计算函数

以常见的1920x1080分辨率为基准(基准字体设为16sp),根据实际屏幕宽度的比例缩放字体大小:

// 基准分辨率宽度和基准字体大小
private const val BASE_SCREEN_WIDTH = 1920
private const val BASE_FONT_SIZE = 16

fun calculateRelativeFontSize(currentScreenWidth: Int): Float {
    // 按宽度比例计算,也可以结合高度取最小值更稳妥
    val scaleRatio = currentScreenWidth.toFloat() / BASE_SCREEN_WIDTH
    return (BASE_FONT_SIZE * scaleRatio).coerceIn(12f, 24f) // 限制字体大小范围,避免过小或过大
}

说明

  • 上述代码在Linux环境下可直接运行,AWT API跨平台兼容Linux、Windows和macOS
  • 如果需要更精细的适配,可以结合屏幕的DPI值调整,可通过screen.defaultTransform.scaleX获取DPI缩放比例
  • 字体大小使用sp单位时,Compose会自动处理系统的字体缩放设置,结合比例计算能实现更全面的自适应

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:25:09