ScreenUtil is a Compose Multiplatform library designed to easily adapt their UI to different screen sizes. Inspired by flutter_screenutil.
- Automatic screen adaptation based on design draft size
- Support for width
.w, height.h, and responsive scaling.r 1.swand1.shBased on screen width and height.(e.g., 0.5.sw = screen half width, 0.3.sh = 30% screen height)rspFont size scaling support
Add the dependency to your build.gradle.kts file:
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("io.github.classops:kmp-screenutil:1.0.0")
}
}
}
}Wrap your app's content with the [ScreenUtil] composable and specify your design draft size:
@Composable
fun App() {
// design draft size
ScreenUtil(designSize = IntSize(360, 710)) {
// Your app content here
MyScreen()
}
}Once initialized, you can use the following extension properties:
Float.w/Int.w- Scales based on width ratioFloat.h/Int.h- Scales based on height ratioFloat.r/Int.r- Scales based on the minimum of width and height ratios (responsive)
Example:
Box(
modifier = Modifier
.size(100.w, 50.h) // Width scaled to 100dp equivalent, height to 50dp equivalent
.padding(10.r) // Responsive padding
)Number.rsp- Scales font size responsively
Example:
Text(
text = "Hello World",
fontSize = 16.rsp
)Number.sw- Percentage of screen width (e.g., 0.5.sw = half screen width)Number.sh- Percentage of screen height (e.g., 0.3.sh = 30% of screen height)
Example:
Box(
modifier = Modifier
.width(0.8.sw) // 80% of screen width
.height(0.6.sh) // 60% of screen height
)You can customize the behavior of ScreenUtil:
ScreenUtil(
designSize = IntSize(390, 844), // iPhone 14 Pro design size
enableFontScale = false // Disable system font scaling
) {
// Your content here
}The ScreenUtil object provides utility methods and properties:
Methods:
w(dp: Int): Dp- Scale by width ratioh(dp: Int): Dp- Scale by height ratio
Properties:
density: Float- Device densitywScale: Float/hScale: Float- Scaling factorsscreenWidthDp: Int/screenHeightDp: Int- Screen dimensionsdesignWidthDp: Int/designHeightDp: Int- Design draft dimensions
ScreenUtil calculates scaling factors by comparing the actual device screen size to your design draft size:
wScale= deviceWidth / designWidthhScale= deviceHeight / designHeight
These scales are then applied to your dimensions when using the extension properties, ensuring consistent visual proportions across devices of different sizes.
As a Compose Multiplatform library, ScreenUtil works on:
- Android
- iOS
- Desktop (Windows, macOS, Linux)
- Web