Reputation: 144
I have an image resource. I convert it to Bitmap. All I want is to rotate it around the center of the screen. If the rotated Bitmap extends the screen, it should be cut. The entire app looks like this
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TestTheme {
Box {
val imageBitmap: ImageBitmap = BitmapFactory
.decodeResource(resources, R.raw.photo)
.rotate(45f, this@MainActivity)
.asImageBitmap()
Canvas(modifier = Modifier.fillMaxSize()) {
drawImage(imageBitmap)
}
}
}
}
}
}
fun Bitmap.rotate(angle: Float, context: Context): Bitmap {
val metrics = context.resources.displayMetrics
val matrix = Matrix().apply {
setRotate(angle.toFloat(), metrics.widthPixels / 2f, metrics.heightPixels / 2f)
}
return Bitmap.createBitmap(this, 0, 0, metrics.widthPixels, metrics.heightPixels, matrix, true)
}
The problem with this code is the image is rotated, but the center is definitely not the center of the screen. Moreover, I can replace metrics.widthPixels / 2f
, metrics.heightPixels / 2f
in setRotate
with absolutely different values, but the result is the same.
Looks like these values are replaced when bitmap is rendered. What is the proper way to observe rotation in Compose?
Upvotes: 0
Views: 38
Reputation: 134714
You can use the rotate
Modifier
to make this much more efficient. For example:
Image(
painterResource(R.raw.photo),
contentDescription = null,
modifier = Modifier.wrapContentSize().rotate(45f),
)
The default pivot point is the center of the composable.
You can still do the same if you have a Bitmap
, just pass the ImageBitmap
to the Image
composable.
Upvotes: 1