Android jetpack compose 全屏显示网络图片,可缩放拖拽,双击还原,单击关闭
前言
jetpack compose 真的是个好东西,以前老费劲才能弄出来的效果,用它几行代码就能实现了,真香。
依赖
我这边加载网络图片使用的是coil,因为它出了兼容compose的版本。
implementation("io.coil-kt:coil:1.4.0")
implementation("io.coil-kt:coil-compose:1.4.0")
代码
全屏显示图片的组件
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import coil.compose.rememberImagePainter
@Composable
fun FullScreenImage(
modifier: Modifier = Modifier,
url: String,
onClick: () -> Unit = {}
) {
var scale by remember { mutableStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val state = rememberTransformableState { zoomChange, _, _ ->
scale = (zoomChange * scale) .coerceAtLeast(1f)
}
Surface(
color = Color.DarkGray,
modifier = modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(
onDoubleTap = {
scale = 1f
offset = Offset.Zero
},
onTap = {
onClick.invoke()
}
)
}
) {
Image(
painter = rememberImagePainter(url),
contentDescription = "",
modifier = Modifier
.fillMaxSize()
.transformable(state = state)
.graphicsLayer(
scaleX = scale,
scaleY = scale,
translationX = offset.x,
translationY = offset.y
)
.pointerInput(Unit) {
detectDragGestures { _, dragAmount ->
offset += dragAmount
}
}
)
}
}
使用
var isShowImageFullScreen by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier
.fillMaxSize()
.background(lightBackground)
.navigationBarsPadding()
) {
Button(onClick = { isShowImageFullScreen = true }) {
Text(text = "显示图片")
}
}
if (isShowImageFullScreen) {
FullScreenImage(url = "https://profile.csdnimg.cn/A/0/9/1_sinat_38184748") {
isShowImageFullScreen = false
}
}
完事
|