如何在Jetpack compose中实现图像缩放?

问题描述 投票:0回答:2

Jetpack 中像 Instagram 一样的图像缩放,如果有人可以帮忙的话

我想要这样的东西 https://drive.google.com/file/d/18a7SaPIoSObbvrmYxJ0GDhHXEETKpsEV/view?usp=drivesdk

android kotlin user-interface android-jetpack-compose
2个回答
9
投票

1- 将比例保存为状态

var scale by remember { mutableStateOf(1f) }

2- 设置图像的比例以使用此状态。我建议使用 GraphicsLayer 设置比例,以最大限度地减少无效内容,并添加您想要的任何其他转换,如下所示

Image(
        ...,
        modifier = Modifier
            .graphicsLayer(
                scaleX = scale,
                scaleY = scale
            )
    )

3- 使用

Modifier.pointerInput
检测并应用缩放效果。使用 PointerInputScope,您可以检测选项卡和转换(缩放、旋转和平移)。例如,您可以添加以下内容来检测缩放手势并相应地修改比例。

modifier = Modifier
            .pointerInput(Unit) {
                detectTransformGestures { _, _, zoom, _ ->
                    scale = (scale * zoom).coerceIn(0.5f, 3f)
                }
            }

detectTransformGestures
的其他参数是质心、平移和旋转。您不需要它们来进行缩放变换,但如果您尝试应用旋转和平移,则需要它们。

如果您想使用平移手势应用缩放,您可以使用

detectTapGestures
。这是一个例子。

modifier = Modifier
            .pointerInput(Unit) {
                detectTapGestures(
                    onDoubleTap = {
                        scale = if (scale > 2f) 1f else 3f
                    }
                )
            }

这是使用 CoilImage 的完整示例。任何其他图像的实现应该是相同的

@Composable fun SamplePreview(imageUrl: String) {
var scale by remember { mutableStateOf(1f) }
Box {
    CoilImage(
        data = imageUrl,
        contentDescription = null,
        contentScale = ContentScale.FillWidth,
        modifier = Modifier
            .align(Alignment.Center)
            .graphicsLayer(
                scaleX = scale,
                scaleY = scale
            )
            .pointerInput(Unit) {
                detectTransformGestures { _, _, zoom, _ ->
                    scale = (scale * zoom).coerceIn(0.5f, 3f)
                }
            }
    ) {
        CircularProgressIndicator()
    }
}

0
投票

你有进步吗?我可以缩放图像,但当用户终止手势时,无法将图像恢复到原始大小。 为了缩放图像,我所做的是: 创建了尺度和状态变量。

if(scale < 1)
是为了不让用户最小化图像。

var scale by remember { mutableStateOf(1f) }
val state = rememberTransformableState { zoomChange, _, _ ->
                scale *= zoomChange
                if(scale < 1){
                    scale = 1F
                }
        }

在图像中,我使用了graphicsLayer 和transformable。

.graphicsLayer{
                    scaleX = scale;
                    scaleY = scale
                }
.transformable(state = state)

我尝试捕获用户的MotionEvent,但没有找到观察到捏合手势的MotionEvent。 另外,在

.pointerInput
中,我不能同时使用
detectTapGestures
detectTransformGestures
,因为指针只考虑一个。

© www.soinside.com 2019 - 2024. All rights reserved.