Kotlin Multiplatform(KMP)의 데스크탑에서 화면 캡처 기능이 필요한 경우, Java AWT의 Robot
클래스를 활용하여 지정된 화면 영역을 이미지로 저장할 수 있다.
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import java.awt.*
import java.io.File
import javax.imageio.ImageIO
// 지정된 영역을 캡처하여 PNG 이미지로 저장
fun saveScreenImage(rectangle: Rectangle) {
try {
val screenImage = Robot().createScreenCapture(rectangle)
val fileFrame = Frame("이미지 저장")
val fileDialog = FileDialog(fileFrame, "이미지 저장", FileDialog.SAVE)
fileDialog.isVisible = true
if (fileDialog.file == null) return
val fileName = File(fileDialog.directory, "${fileDialog.file}.png")
ImageIO.write(screenImage, "png", fileName)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(800.dp, 1000.dp))
Window(
onCloseRequest = ::exitApplication,
title = "",
state = windowState
) {
App(
onScreenSave = {
val rectangle = Rectangle(
window.locationOnScreen.x,
window.locationOnScreen.y,
window.width,
window.height
)
saveScreenImage(rectangle)
}
)
}
}