android
Android Bitmap rotate, resize, combine Kotlin
무삿
2023. 7. 28. 19:06
개인 프로젝트를 진행하며 비트맵을 다루게 되어 세가지 함수를 만들었다. 다른 분들도 도움이 되길 바라면서 사용했으면 싶어서 소개한다.
1. rotate Bitmap - 비트맵 회전
fun rotateBitmap(bitmap: Bitmap, angle: Float): Bitmap {
val matrix = Matrix()
matrix.setRotate(angle)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
예시
rotateBitmap(pictureImg.toBitmap(), 90f)
시계 방향 90도 회전된 비트맵을 만들어준다.
2. resize Bitmap - 비트맵 사이즈 변경
fun resizeBitmap(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
}
예시
val resizedCapture = resizeBitmap(
captureImg.asAndroidBitmap(),
rotatedPicture.width,
rotatedPicture.height
)
3. combined Bitmap - 비트맵 합성
fun combineBitmap(picture1: Bitmap, picture2: Bitmap): Bitmap {
val resultWidth = max(picture1.width, picture2.width)
val resultHeight = max(picture1.height, picture2.height)
val resultBitmap = Bitmap.createBitmap(resultWidth, resultHeight, picture1.config)
val canvas = Canvas(resultBitmap)
canvas.drawBitmap(picture1, 0f, 0f, Paint())
canvas.drawBitmap(picture2, 0f, 0f, Paint())
return resultBitmap
}
1을 먼저 그리고 그 위에 2를 그린다. 그러므로 위로 올려서 합성하고 싶은 비트맵을 매개변수 picture2의 인자로 사용하면 된다.
3가지 함수를 잘 조합하여 카메라에서 찍은 사진과 별도의 사진을 내가 원하는 규격에 맞게 합성할 수 있다.