简体   繁体   English

带组合的图像裁剪器

[英]Image cropper with compose

I'm trying to implement simple image cropper with compose.我正在尝试用 compose 实现简单的图像裁剪器。 The overlay can be resized and drag over the image.可以调整叠加层的大小并在图像上拖动。 The problem is, it can be dragged out of the image and out of screen too.问题是,它也可以被拖出图像和屏幕。 How to set limits for the overlay to move and resized over the image only?如何设置叠加层的限制以仅在图像上移动和调整大小?

The updated code更新的代码

@Composable
fun ImageCrooper() {
  var size by remember { mutableStateOf(Size.Zero) }
  
  var offsetX by remember { mutableStateOf(0f) }
  var offsetY by remember { mutableStateOf(0f) }
  
  var height by remember { mutableStateOf(140f) }
  var width by remember { mutableStateOf(140f) }
  BoxWithConstraints(
    Modifier
      .fillMaxWidth()
      .height(240.dp)
      .onSizeChanged {
        size = it.toSize()
      }
  ) {
    Image(
      modifier = Modifier
        .fillMaxSize(),
      contentScale = ContentScale.Crop,
      painter = rememberAsyncImagePainter(
        model = "https://i.picsum.photos/id/216/200/200.jpg?hmac=7Weas8POu49YrmUyJ6tWdqVMx-hw6lryzl8HnHZBzjc"
      ),
      contentDescription = "A Content description",
    )
    BoxWithConstraints(
      modifier = Modifier
        .offset {
          IntOffset(offsetX.roundToInt(), offsetY.roundToInt())
        }
        .height(height.dp)
        .width(width.dp)
    ) {
      //      move the overlay
      Box(
        Modifier
          .background(Color.Black.copy(0.6f))
          .fillMaxSize()
          .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
              change.consumeAllChanges()
              offsetY = (offsetY + dragAmount.y).coerceIn(0f, 230f)
              offsetX = (offsetX + dragAmount.x).coerceIn(0f, size.width)
            }
          }
      )
      //      resize the overlay
      
      Box(
        Modifier
          .align(Alignment.BottomEnd)
          .background(Color.White)
          .height(20.dp)
          .width(20.dp)
          .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
              change.consumeAllChanges()
              width = (width + dragAmount.x).coerceIn(140f, size.width - width)
              height = (height + dragAmount.y).coerceIn(140f, size.height - height)
        
            }
          }
      )
    }
  }
}

You can limit offset variables inside your Composable dimension bounds using coerceIn functions.您可以使用coerceIn函数限制可组合尺寸范围内的偏移变量。 You can get size of your Composable using您可以使用获得可组合的大小

var size by remember { mutableStateOf(Size.Zero) }
Modifier.onSizeChanged {
    size = it.toSize()
}

offsetY = (offsetY + dragAmount.y).coerceIn(0f, size.height)
offsetX = (offsetX + dragAmount.x).coerceIn(0f, size.width)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM