Is there any easy way in Compose to display an Ima...
# compose
m
Is there any easy way in Compose to display an Image rotated by 90˚? I tried it with the
graphicsLayer
modifier and setting
rotationZ
to 90f. That does the rotation but then
contentScale.Fit
does not work anymore because it ignores the rotation. I have a solution by manually computing some scale offset but that looks awkward. Does anybody know of a simple solution?
c
Are you applying graphicsLayer to the image? What if you apply it to a higher level composable? (Like a Box around the image)
e
graphicsLayer doesn't affect layout
the easiest thing to do might be to make a wrapper around BitmapPainter that swaps the size width/height and rotates the canvas before drawing
c
Does ContentScale affect layout? Maybe I misunderstood; is there a problem with layout?
I thought the problem was the content scale did not work with the rotated image
The layout may just be a square
m
I just gave the first proposal by @Chris Fillmore a try but it results in the same problem as before. In my solution I use the modifier
onGloballyPositioned
to get the size of
Image
after the layout and compute a correction factor for the scale. In the modifier
graphicsLayer
I then apply this correction factor by setting
scaleX
and
scaleY
in addition to applying the rotation via
rotationZ
. This has to be done though via an intermediate remembered mutable state to get the scale offset from
onGloballyPositioned
to
graphicsLayer
. (At least I think so.) This works nicely but it feels like a hack and I think
Image
should be able to handle that use-case directly.
e
what I was saying,
Copy code
class RotatePainter(val painter: Painter) : Painter() {
    override val intrinsicSize: Size
        get() = Size(painter.intrinsicSize.height, painter.intrinsicSize.width)

    override fun DrawScope.onDraw() {
        withTransform(
            transformBlock = {
                val delta = (size.width - size.height) / 2
                inset(delta, -delta, delta, -delta)
                rotate(90f)
            },
            drawBlock = { with(painter) { draw(size) } }
        )
    }
}
if you use
Image(painter = RotatePainter(bitmapPainter))
instead of
Image(painter = bitmapPainter)
(or whatever image source you have), it should do all the "right" things with regards to
contentScale
, intrinsic sizes, etc.
🙏 1
m
Ahh, that looks shorter and more straight forward than my own solution. I’ll give that a try too. Thank you very much so far.
It works and it is even more performant than my solution. Thanks a lot.
1