提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
@@ -0,0 +1,43 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.feature.imagetools"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(project(":core:ui"))
implementation(project(":core:ffmpeg"))
implementation(libs.activity.compose)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
implementation(libs.hilt.navigation.compose)
implementation(libs.lifecycle.viewmodel)
testImplementation(libs.junit)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,201 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.ClipOp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
private const val HANDLE_HIT_RADIUS_DP = 32f
private const val HANDLE_VISUAL_RADIUS_DP = 10f
@Composable
fun CropOverlay(
bitmap: Bitmap,
corners: List<Offset>,
onCornerMoved: (index: Int, newPosition: Offset) -> Unit,
modifier: Modifier = Modifier,
) {
var viewSize by remember { mutableStateOf(IntSize.Zero) }
var zoom by remember { mutableFloatStateOf(1f) }
var panOffset by remember { mutableStateOf(Offset.Zero) }
var activeCorner by remember { mutableIntStateOf(-1) }
val currentCorners by rememberUpdatedState(corners)
val currentOnCornerMoved by rememberUpdatedState(onCornerMoved)
val imageBitmap = remember(bitmap) { bitmap.asImageBitmap() }
val density = androidx.compose.ui.platform.LocalDensity.current.density
fun fitParams(): FloatArray {
if (viewSize == IntSize.Zero) return floatArrayOf(0f, 0f, 0f, 0f)
val fitScale = minOf(
viewSize.width.toFloat() / bitmap.width,
viewSize.height.toFloat() / bitmap.height,
)
val imgW = bitmap.width * fitScale
val imgH = bitmap.height * fitScale
val imgLeft = (viewSize.width - imgW) / 2f
val imgTop = (viewSize.height - imgH) / 2f
return floatArrayOf(imgLeft, imgTop, imgW, imgH)
}
fun imageToScreen(normalized: Offset): Offset {
val (imgLeft, imgTop, imgW, imgH) = fitParams()
return Offset(
(imgLeft + normalized.x * imgW) * zoom + panOffset.x,
(imgTop + normalized.y * imgH) * zoom + panOffset.y,
)
}
fun screenDeltaToNormalized(dx: Float, dy: Float): Offset {
val (_, _, imgW, imgH) = fitParams()
return Offset(dx / (imgW * zoom), dy / (imgH * zoom))
}
fun nearestCorner(screenPos: Offset, hitRadiusPx: Float): Int {
var best = -1
var bestDist = hitRadiusPx * hitRadiusPx
currentCorners.forEachIndexed { i, corner ->
val sp = imageToScreen(corner)
val dist = (sp.x - screenPos.x) * (sp.x - screenPos.x) +
(sp.y - screenPos.y) * (sp.y - screenPos.y)
if (dist < bestDist) { bestDist = dist; best = i }
}
return best
}
val accentColor = MaterialTheme.colorScheme.primary
val dimColor = Color.Black.copy(alpha = 0.5f)
Box(
modifier = modifier
.fillMaxSize()
.onGloballyPositioned { viewSize = it.size }
.pointerInput(Unit) {
val hitRadiusPx = HANDLE_HIT_RADIUS_DP * density
awaitEachGesture {
val down = awaitFirstDown(pass = PointerEventPass.Main)
val hit = nearestCorner(down.position, hitRadiusPx)
if (hit >= 0) {
down.consume()
activeCorner = hit
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
val change = event.changes.firstOrNull() ?: break
if (change.changedToUp()) break
val delta = change.positionChange()
if (delta != Offset.Zero) {
change.consume()
val nd = screenDeltaToNormalized(delta.x, delta.y)
val cur = currentCorners[activeCorner]
currentOnCornerMoved(
activeCorner,
Offset(
(cur.x + nd.x).coerceIn(0f, 1f),
(cur.y + nd.y).coerceIn(0f, 1f),
),
)
}
}
activeCorner = -1
} else {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
val pressed = event.changes.filter { it.pressed }
if (pressed.isEmpty()) break
if (pressed.size >= 2) {
val (a, b) = pressed
val oldDist = (a.previousPosition - b.previousPosition).getDistance()
val newDist = (a.position - b.position).getDistance()
if (oldDist > 0f) zoom = (zoom * (newDist / oldDist)).coerceIn(0.5f, 10f)
val centroidDelta = pressed.map { it.positionChange() }
.reduce { acc, o -> acc + o } / pressed.size.toFloat()
panOffset += centroidDelta
pressed.forEach { it.consume() }
} else {
val change = pressed.first()
val delta = change.positionChange()
if (delta != Offset.Zero) { panOffset += delta; change.consume() }
}
}
}
}
},
) {
if (viewSize == IntSize.Zero) return@Box
val (imgLeft, imgTop, imgW, imgH) = fitParams()
Canvas(
modifier = Modifier.fillMaxSize().graphicsLayer {
scaleX = zoom; scaleY = zoom
translationX = panOffset.x; translationY = panOffset.y
},
) {
drawImage(
imageBitmap,
dstSize = IntSize(imgW.roundToInt(), imgH.roundToInt()),
dstOffset = IntOffset(imgLeft.roundToInt(), imgTop.roundToInt()),
)
}
val handleRadiusPx = HANDLE_VISUAL_RADIUS_DP * density
Canvas(modifier = Modifier.fillMaxSize()) {
val sc = currentCorners.map { imageToScreen(it) }
val xs = sc.map { it.x }
val ys = sc.map { it.y }
val cropRect = Rect(xs.min(), ys.min(), xs.max(), ys.max())
val cropPath = Path().apply { addRect(cropRect) }
clipPath(cropPath, ClipOp.Difference) {
drawRect(dimColor)
}
drawRect(accentColor, topLeft = cropRect.topLeft, size = cropRect.size, style = Stroke(2.dp.toPx()))
// Rule-of-thirds grid
for (i in 1..2) {
val fx = i / 3f
val x = cropRect.left + cropRect.width * fx
drawLine(accentColor.copy(alpha = 0.3f), Offset(x, cropRect.top), Offset(x, cropRect.bottom))
val y = cropRect.top + cropRect.height * fx
drawLine(accentColor.copy(alpha = 0.3f), Offset(cropRect.left, y), Offset(cropRect.right, y))
}
sc.forEachIndexed { i, pos ->
drawCircle(Color.Black.copy(alpha = 0.4f), handleRadiusPx + 2.dp.toPx(), pos)
drawCircle(if (i == activeCorner) Color.White else accentColor, handleRadiusPx, pos)
drawCircle(if (i == activeCorner) accentColor else Color.White, handleRadiusPx * 0.3f, pos)
}
}
}
}
@@ -0,0 +1,23 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
sealed interface ImageToolState {
data object Idle : ImageToolState
data object Loading : ImageToolState
data class Loaded(
val bitmap: Bitmap,
val cachePath: String,
val fileName: String,
val width: Int,
val height: Int,
) : ImageToolState
data class Processing(val label: String) : ImageToolState
data class Preview(
val original: Bitmap,
val result: Bitmap,
val resultCachePath: String,
val fileName: String,
) : ImageToolState
data class Error(val message: String) : ImageToolState
}
@@ -0,0 +1,265 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Undo
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Crop
import androidx.compose.material.icons.filled.GridOn
import androidx.compose.material.icons.filled.RotateRight
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.ZoomIn
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
enum class Tool(val labelRes: Int, val icon: ImageVector) {
VIEW(R.string.imagetools_view, Icons.Filled.ZoomIn),
CROP(R.string.imagetools_crop, Icons.Filled.Crop),
ROTATE(R.string.imagetools_rotate, Icons.Filled.RotateRight),
PERSPECTIVE(R.string.imagetools_perspective, Icons.Filled.GridOn),
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageToolsScreen(
state: ImageToolState,
saving: Boolean = false,
onApplyPerspective: (corners: List<Offset>, width: Int, height: Int) -> Unit,
onApplyCrop: (left: Float, top: Float, right: Float, bottom: Float, width: Int, height: Int) -> Unit,
onApplyRotate: (degrees: Float, width: Int, height: Int) -> Unit,
onSave: () -> Unit,
onReset: () -> Unit,
onBack: () -> Unit,
) {
var tool by rememberSaveable { mutableStateOf(Tool.VIEW) }
var perspCorners by remember {
mutableStateOf(
listOf(
Offset(0.05f, 0.05f), Offset(0.95f, 0.05f),
Offset(0.05f, 0.95f), Offset(0.95f, 0.95f),
)
)
}
var cropCorners by remember {
mutableStateOf(
listOf(
Offset(0.1f, 0.1f), Offset(0.9f, 0.1f),
Offset(0.1f, 0.9f), Offset(0.9f, 0.9f),
)
)
}
var rotateDegrees by remember { mutableFloatStateOf(0f) }
var showOriginal by remember { mutableStateOf(false) }
fun resetCurrentTool() {
when (tool) {
Tool.PERSPECTIVE -> perspCorners = listOf(
Offset(0.05f, 0.05f), Offset(0.95f, 0.05f),
Offset(0.05f, 0.95f), Offset(0.95f, 0.95f),
)
Tool.CROP -> cropCorners = listOf(
Offset(0.1f, 0.1f), Offset(0.9f, 0.1f),
Offset(0.1f, 0.9f), Offset(0.9f, 0.9f),
)
Tool.ROTATE -> rotateDegrees = 0f
else -> {}
}
}
Scaffold(
topBar = {
TopAppBar(
title = {
val title = when (state) {
is ImageToolState.Loaded -> state.fileName
is ImageToolState.Preview -> state.fileName
is ImageToolState.Loading -> stringResource(R.string.imagetools_loading)
is ImageToolState.Processing -> state.label
else -> stringResource(R.string.imagetools_title)
}
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
},
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null)
}
},
actions = {
when (state) {
is ImageToolState.Loaded -> if (tool != Tool.VIEW) {
IconButton(onClick = { resetCurrentTool() }) {
Icon(Icons.AutoMirrored.Filled.Undo, stringResource(R.string.imagetools_reset))
}
IconButton(onClick = {
when (tool) {
Tool.PERSPECTIVE -> onApplyPerspective(perspCorners, state.width, state.height)
Tool.CROP -> {
val xs = cropCorners.map { it.x }
val ys = cropCorners.map { it.y }
onApplyCrop(xs.min(), ys.min(), xs.max(), ys.max(), state.width, state.height)
}
Tool.ROTATE -> onApplyRotate(rotateDegrees, state.width, state.height)
else -> {}
}
}) {
Icon(Icons.Filled.Check, stringResource(R.string.imagetools_apply))
}
}
is ImageToolState.Preview -> {
IconButton(onClick = { onReset(); tool = Tool.VIEW }) {
Icon(Icons.AutoMirrored.Filled.Undo, stringResource(R.string.imagetools_reset))
}
IconButton(onClick = onSave, enabled = !saving) {
Icon(Icons.Filled.Save, stringResource(R.string.imagetools_save))
}
}
else -> {}
}
},
)
},
bottomBar = {
if (state is ImageToolState.Loaded || state is ImageToolState.Preview) {
NavigationBar {
Tool.entries.forEach { t ->
NavigationBarItem(
selected = tool == t,
onClick = {
if (state is ImageToolState.Preview && t != tool) {
onReset()
}
tool = t
},
icon = { Icon(t.icon, contentDescription = null) },
label = { Text(stringResource(t.labelRes)) },
)
}
}
}
},
) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding).fillMaxSize()) {
when (val current = state) {
is ImageToolState.Idle -> {}
is ImageToolState.Loading -> {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
}
is ImageToolState.Processing -> {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
CircularProgressIndicator()
Text(current.label, style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 16.dp))
}
}
}
is ImageToolState.Error -> {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.imagetools_failed, current.message),
color = MaterialTheme.colorScheme.error)
}
}
is ImageToolState.Loaded -> {
when (tool) {
Tool.VIEW -> {
ZoomableImage(bitmap = current.bitmap)
}
Tool.PERSPECTIVE -> {
PerspectiveOverlay(
bitmap = current.bitmap,
corners = perspCorners,
onCornerMoved = { i, pos ->
perspCorners = perspCorners.toMutableList().also { it[i] = pos }
},
)
}
Tool.CROP -> {
CropOverlay(
bitmap = current.bitmap,
corners = cropCorners,
onCornerMoved = { i, pos ->
// Couple corners to maintain a rectangle:
// 0=TL 1=TR 2=BL 3=BR
val c = cropCorners.toMutableList()
c[i] = pos
when (i) {
0 -> { c[1] = c[1].copy(y = pos.y); c[2] = c[2].copy(x = pos.x) }
1 -> { c[0] = c[0].copy(y = pos.y); c[3] = c[3].copy(x = pos.x) }
2 -> { c[0] = c[0].copy(x = pos.x); c[3] = c[3].copy(y = pos.y) }
3 -> { c[1] = c[1].copy(x = pos.x); c[2] = c[2].copy(y = pos.y) }
}
cropCorners = c
},
)
}
Tool.ROTATE -> {
RotateOverlay(
bitmap = current.bitmap,
degrees = rotateDegrees,
onDegreesChanged = { rotateDegrees = it },
)
}
}
}
is ImageToolState.Preview -> {
Column(modifier = Modifier.fillMaxSize()) {
Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp)) {
FilterChip(
selected = showOriginal,
onClick = { showOriginal = true },
label = { Text(stringResource(R.string.imagetools_original)) },
)
Spacer(Modifier.width(8.dp))
FilterChip(
selected = !showOriginal,
onClick = { showOriginal = false },
label = { Text(stringResource(R.string.imagetools_result)) },
)
}
val bmp = if (showOriginal) current.original else current.result
ZoomableImage(bitmap = bmp, modifier = Modifier.fillMaxSize().padding(8.dp))
}
}
}
}
}
}
@@ -0,0 +1,212 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
private const val HANDLE_HIT_RADIUS_DP = 32f
private const val HANDLE_VISUAL_RADIUS_DP = 10f
@Composable
fun PerspectiveOverlay(
bitmap: Bitmap,
corners: List<Offset>,
onCornerMoved: (index: Int, newPosition: Offset) -> Unit,
modifier: Modifier = Modifier,
) {
var viewSize by remember { mutableStateOf(IntSize.Zero) }
var zoom by remember { mutableFloatStateOf(1f) }
var panOffset by remember { mutableStateOf(Offset.Zero) }
var activeCorner by remember { mutableIntStateOf(-1) }
val currentCorners by rememberUpdatedState(corners)
val currentOnCornerMoved by rememberUpdatedState(onCornerMoved)
val imageBitmap = remember(bitmap) { bitmap.asImageBitmap() }
fun fitParams(): FloatArray {
if (viewSize == IntSize.Zero) return floatArrayOf(0f, 0f, 0f, 0f)
val fitScale = minOf(
viewSize.width.toFloat() / bitmap.width,
viewSize.height.toFloat() / bitmap.height,
)
val imgW = bitmap.width * fitScale
val imgH = bitmap.height * fitScale
val imgLeft = (viewSize.width - imgW) / 2f
val imgTop = (viewSize.height - imgH) / 2f
return floatArrayOf(imgLeft, imgTop, imgW, imgH)
}
fun imageToScreen(normalized: Offset): Offset {
val (imgLeft, imgTop, imgW, imgH) = fitParams()
val x = (imgLeft + normalized.x * imgW) * zoom + panOffset.x
val y = (imgTop + normalized.y * imgH) * zoom + panOffset.y
return Offset(x, y)
}
fun screenDeltaToNormalized(dx: Float, dy: Float): Offset {
val (_, _, imgW, imgH) = fitParams()
return Offset(dx / (imgW * zoom), dy / (imgH * zoom))
}
fun nearestCorner(screenPos: Offset, hitRadiusPx: Float): Int {
var best = -1
var bestDist = hitRadiusPx * hitRadiusPx
currentCorners.forEachIndexed { i, corner ->
val sp = imageToScreen(corner)
val dist = (sp.x - screenPos.x) * (sp.x - screenPos.x) +
(sp.y - screenPos.y) * (sp.y - screenPos.y)
if (dist < bestDist) {
bestDist = dist
best = i
}
}
return best
}
val accentColor = MaterialTheme.colorScheme.primary
val lineColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.8f)
val density = androidx.compose.ui.platform.LocalDensity.current.density
Box(
modifier = modifier
.fillMaxSize()
.onGloballyPositioned { viewSize = it.size }
.pointerInput(Unit) {
val hitRadiusPx = HANDLE_HIT_RADIUS_DP * density
awaitEachGesture {
val down = awaitFirstDown(pass = PointerEventPass.Main)
val hit = nearestCorner(down.position, hitRadiusPx)
if (hit >= 0) {
// Corner drag
down.consume()
activeCorner = hit
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
val change = event.changes.firstOrNull() ?: break
if (change.changedToUp()) break
val delta = change.positionChange()
if (delta != Offset.Zero) {
change.consume()
val nd = screenDeltaToNormalized(delta.x, delta.y)
val cur = currentCorners[activeCorner]
currentOnCornerMoved(
activeCorner,
Offset(
(cur.x + nd.x).coerceIn(0f, 1f),
(cur.y + nd.y).coerceIn(0f, 1f),
),
)
}
}
activeCorner = -1
} else {
// Pan / pinch-to-zoom
while (true) {
val event = awaitPointerEvent(PointerEventPass.Main)
val pressed = event.changes.filter { it.pressed }
if (pressed.isEmpty()) break
if (pressed.size >= 2) {
val (a, b) = pressed
val oldDist = (a.previousPosition - b.previousPosition).getDistance()
val newDist = (a.position - b.position).getDistance()
if (oldDist > 0f) {
zoom = (zoom * (newDist / oldDist)).coerceIn(0.5f, 10f)
}
val centroidDelta = pressed.map { it.positionChange() }
.reduce { acc, o -> acc + o } / pressed.size.toFloat()
panOffset += centroidDelta
pressed.forEach { it.consume() }
} else {
val change = pressed.first()
val delta = change.positionChange()
if (delta != Offset.Zero) {
panOffset += delta
change.consume()
}
}
}
}
}
},
) {
if (viewSize == IntSize.Zero) return@Box
val (imgLeft, imgTop, imgW, imgH) = fitParams()
Canvas(
modifier = Modifier
.fillMaxSize()
.graphicsLayer {
scaleX = zoom
scaleY = zoom
translationX = panOffset.x
translationY = panOffset.y
},
) {
drawImage(
imageBitmap,
dstSize = IntSize(imgW.roundToInt(), imgH.roundToInt()),
dstOffset = IntOffset(imgLeft.roundToInt(), imgTop.roundToInt()),
)
}
val handleRadiusPx = HANDLE_VISUAL_RADIUS_DP * density
Canvas(modifier = Modifier.fillMaxSize()) {
val screenCorners = currentCorners.map { imageToScreen(it) }
val path = Path().apply {
moveTo(screenCorners[0].x, screenCorners[0].y)
lineTo(screenCorners[1].x, screenCorners[1].y)
lineTo(screenCorners[3].x, screenCorners[3].y)
lineTo(screenCorners[2].x, screenCorners[2].y)
close()
}
drawPath(path, lineColor, style = Stroke(width = 2.dp.toPx()))
screenCorners.forEachIndexed { i, pos ->
drawCircle(Color.Black.copy(alpha = 0.4f), handleRadiusPx + 2.dp.toPx(), pos)
drawCircle(
if (i == activeCorner) Color.White else accentColor,
handleRadiusPx,
pos,
)
drawCircle(
if (i == activeCorner) accentColor else Color.White,
handleRadiusPx * 0.3f,
pos,
)
}
}
}
}
private operator fun FloatArray.component6(): Float = this[5]
@@ -0,0 +1,93 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import java.util.Locale
@Composable
fun RotateOverlay(
bitmap: Bitmap,
degrees: Float,
onDegreesChanged: (Float) -> Unit,
modifier: Modifier = Modifier,
) {
var zoom by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val imageBitmap = remember(bitmap) { bitmap.asImageBitmap() }
Column(modifier = modifier.fillMaxSize()) {
Image(
bitmap = imageBitmap,
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.pointerInput(Unit) {
detectTransformGestures { _, pan, gestureZoom, gestureRotation ->
zoom = (zoom * gestureZoom).coerceIn(0.5f, 10f)
offset += pan
onDegreesChanged((degrees + gestureRotation).coerceIn(-180f, 180f))
}
}
.graphicsLayer {
scaleX = zoom
scaleY = zoom
translationX = offset.x
translationY = offset.y
rotationZ = degrees
},
)
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(
String.format(Locale.US, "%.1f\u00B0", degrees),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Slider(
value = degrees,
onValueChange = onDegreesChanged,
valueRange = -180f..180f,
modifier = Modifier.fillMaxWidth(),
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
listOf(-90f, -45f, 0f, 45f, 90f, 180f).forEach { preset ->
FilterChip(
selected = degrees == preset,
onClick = { onDegreesChanged(preset) },
label = { Text("${preset.toInt()}\u00B0") },
)
}
}
}
}
}
@@ -0,0 +1,48 @@
package sh.haven.feature.imagetools
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
@Composable
fun ZoomableImage(
bitmap: Bitmap,
modifier: Modifier = Modifier,
) {
var zoom by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val imageBitmap = remember(bitmap) { bitmap.asImageBitmap() }
Image(
bitmap = imageBitmap,
contentDescription = null,
contentScale = ContentScale.Fit,
modifier = modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTransformGestures { _, pan, gestureZoom, _ ->
zoom = (zoom * gestureZoom).coerceIn(0.5f, 10f)
offset += pan
}
}
.graphicsLayer {
scaleX = zoom
scaleY = zoom
translationX = offset.x
translationY = offset.y
},
)
}
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">أدوات الصور</string>
<string name="imagetools_perspective">المنظور</string>
<string name="imagetools_crop">قص</string>
<string name="imagetools_rotate">تدوير</string>
<string name="imagetools_apply">تطبيق</string>
<string name="imagetools_save">حفظ</string>
<string name="imagetools_reset">إعادة تعيين</string>
<string name="imagetools_original">الأصل</string>
<string name="imagetools_result">النتيجة</string>
<string name="imagetools_processing">جارٍ المعالجة…</string>
<string name="imagetools_failed">فشل: %s</string>
<string name="imagetools_saved">تم حفظ %s</string>
<string name="imagetools_open">أدوات الصور</string>
<string name="imagetools_view">عرض</string>
<string name="imagetools_loading">جارٍ تحميل الصورة…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">ইমেজ টুলস</string>
<string name="imagetools_perspective">পরিপ্রেক্ষিত</string>
<string name="imagetools_crop">ক্রপ</string>
<string name="imagetools_rotate">ঘোরান</string>
<string name="imagetools_apply">প্রয়োগ করুন</string>
<string name="imagetools_save">সংরক্ষণ</string>
<string name="imagetools_reset">রিসেট</string>
<string name="imagetools_original">মূল</string>
<string name="imagetools_result">ফলাফল</string>
<string name="imagetools_processing">প্রসেস হচ্ছে…</string>
<string name="imagetools_failed">ব্যর্থ: %s</string>
<string name="imagetools_saved">%s সংরক্ষিত হয়েছে</string>
<string name="imagetools_open">ইমেজ টুলস</string>
<string name="imagetools_view">দেখুন</string>
<string name="imagetools_loading">ইমেজ লোড হচ্ছে…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Bildwerkzeuge</string>
<string name="imagetools_perspective">Perspektive</string>
<string name="imagetools_crop">Zuschneiden</string>
<string name="imagetools_rotate">Drehen</string>
<string name="imagetools_apply">Anwenden</string>
<string name="imagetools_save">Speichern</string>
<string name="imagetools_reset">Zurücksetzen</string>
<string name="imagetools_original">Original</string>
<string name="imagetools_result">Ergebnis</string>
<string name="imagetools_processing">Wird verarbeitet…</string>
<string name="imagetools_failed">Fehler: %s</string>
<string name="imagetools_saved">%s gespeichert</string>
<string name="imagetools_open">Bildwerkzeuge</string>
<string name="imagetools_view">Ansehen</string>
<string name="imagetools_loading">Bild wird geladen…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Herramientas de imagen</string>
<string name="imagetools_perspective">Perspectiva</string>
<string name="imagetools_crop">Recortar</string>
<string name="imagetools_rotate">Rotar</string>
<string name="imagetools_apply">Aplicar</string>
<string name="imagetools_save">Guardar</string>
<string name="imagetools_reset">Restablecer</string>
<string name="imagetools_original">Original</string>
<string name="imagetools_result">Resultado</string>
<string name="imagetools_processing">Procesando…</string>
<string name="imagetools_failed">Error: %s</string>
<string name="imagetools_saved">Guardado %s</string>
<string name="imagetools_open">Herramientas de imagen</string>
<string name="imagetools_view">Ver</string>
<string name="imagetools_loading">Cargando imagen…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Outils d’image</string>
<string name="imagetools_perspective">Perspective</string>
<string name="imagetools_crop">Recadrer</string>
<string name="imagetools_rotate">Pivoter</string>
<string name="imagetools_apply">Appliquer</string>
<string name="imagetools_save">Enregistrer</string>
<string name="imagetools_reset">Réinitialiser</string>
<string name="imagetools_original">Original</string>
<string name="imagetools_result">Résultat</string>
<string name="imagetools_processing">Traitement…</string>
<string name="imagetools_failed">Échec : %s</string>
<string name="imagetools_saved">%s enregistré</string>
<string name="imagetools_open">Outils d’image</string>
<string name="imagetools_view">Voir</string>
<string name="imagetools_loading">Chargement de l’image…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">इमेज टूल्स</string>
<string name="imagetools_perspective">परिप्रेक्ष्य</string>
<string name="imagetools_crop">क्रॉप</string>
<string name="imagetools_rotate">घुमाएँ</string>
<string name="imagetools_apply">लागू करें</string>
<string name="imagetools_save">सहेजें</string>
<string name="imagetools_reset">रीसेट</string>
<string name="imagetools_original">मूल</string>
<string name="imagetools_result">परिणाम</string>
<string name="imagetools_processing">प्रसंस्करण…</string>
<string name="imagetools_failed">विफल: %s</string>
<string name="imagetools_saved">%s सहेजा गया</string>
<string name="imagetools_open">इमेज टूल्स</string>
<string name="imagetools_view">देखें</string>
<string name="imagetools_loading">इमेज लोड हो रही है…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">画像ツール</string>
<string name="imagetools_perspective">遠近補正</string>
<string name="imagetools_crop">切り抜き</string>
<string name="imagetools_rotate">回転</string>
<string name="imagetools_apply">適用</string>
<string name="imagetools_save">保存</string>
<string name="imagetools_reset">リセット</string>
<string name="imagetools_original">元の画像</string>
<string name="imagetools_result">結果</string>
<string name="imagetools_processing">処理中…</string>
<string name="imagetools_failed">失敗: %s</string>
<string name="imagetools_saved">%s を保存しました</string>
<string name="imagetools_open">画像ツール</string>
<string name="imagetools_view">表示</string>
<string name="imagetools_loading">画像を読み込み中…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">이미지 도구</string>
<string name="imagetools_perspective">원근 보정</string>
<string name="imagetools_crop">자르기</string>
<string name="imagetools_rotate">회전</string>
<string name="imagetools_apply">적용</string>
<string name="imagetools_save">저장</string>
<string name="imagetools_reset">재설정</string>
<string name="imagetools_original">원본</string>
<string name="imagetools_result">결과</string>
<string name="imagetools_processing">처리 중…</string>
<string name="imagetools_failed">실패: %s</string>
<string name="imagetools_saved">%s 저장됨</string>
<string name="imagetools_open">이미지 도구</string>
<string name="imagetools_view">보기</string>
<string name="imagetools_loading">이미지를 불러오는 중…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Ferramentas de imagem</string>
<string name="imagetools_perspective">Perspectiva</string>
<string name="imagetools_crop">Recortar</string>
<string name="imagetools_rotate">Girar</string>
<string name="imagetools_apply">Aplicar</string>
<string name="imagetools_save">Salvar</string>
<string name="imagetools_reset">Redefinir</string>
<string name="imagetools_original">Original</string>
<string name="imagetools_result">Resultado</string>
<string name="imagetools_processing">Processando…</string>
<string name="imagetools_failed">Falha: %s</string>
<string name="imagetools_saved">%s salvo</string>
<string name="imagetools_open">Ferramentas de imagem</string>
<string name="imagetools_view">Ver</string>
<string name="imagetools_loading">Carregando imagem…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Инструменты изображения</string>
<string name="imagetools_perspective">Перспектива</string>
<string name="imagetools_crop">Обрезать</string>
<string name="imagetools_rotate">Повернуть</string>
<string name="imagetools_apply">Применить</string>
<string name="imagetools_save">Сохранить</string>
<string name="imagetools_reset">Сбросить</string>
<string name="imagetools_original">Оригинал</string>
<string name="imagetools_result">Результат</string>
<string name="imagetools_processing">Обработка…</string>
<string name="imagetools_failed">Ошибка: %s</string>
<string name="imagetools_saved">%s сохранено</string>
<string name="imagetools_open">Инструменты изображения</string>
<string name="imagetools_view">Просмотр</string>
<string name="imagetools_loading">Загрузка изображения…</string>
</resources>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Алати за слике</string>
<string name="imagetools_perspective">Перспектива</string>
<string name="imagetools_crop">Опсецање</string>
<string name="imagetools_rotate">Ротирање</string>
<string name="imagetools_apply">Примени</string>
<string name="imagetools_save">Сачувај</string>
<string name="imagetools_reset">Ресетуј</string>
<string name="imagetools_original">Оригинал</string>
<string name="imagetools_result">Резултат</string>
<string name="imagetools_processing">Обрађује се…</string>
<string name="imagetools_failed">Није успело: %s</string>
<string name="imagetools_saved">Сачуван је %s</string>
<string name="imagetools_open">Алати за слике</string>
<string name="imagetools_view">Приказ</string>
<string name="imagetools_loading">Слика се учитава…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">图像工具</string>
<string name="imagetools_perspective">透视校正</string>
<string name="imagetools_crop">裁剪</string>
<string name="imagetools_rotate">旋转</string>
<string name="imagetools_apply">应用</string>
<string name="imagetools_save">保存</string>
<string name="imagetools_reset">重置</string>
<string name="imagetools_original">原图</string>
<string name="imagetools_result">结果</string>
<string name="imagetools_processing">正在处理…</string>
<string name="imagetools_failed">失败:%s</string>
<string name="imagetools_saved">已保存 %s</string>
<string name="imagetools_open">图像工具</string>
<string name="imagetools_view">查看</string>
<string name="imagetools_loading">正在加载图像…</string>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="imagetools_title">Image Tools</string>
<string name="imagetools_perspective">Perspective</string>
<string name="imagetools_crop">Crop</string>
<string name="imagetools_rotate">Rotate</string>
<string name="imagetools_apply">Apply</string>
<string name="imagetools_save">Save</string>
<string name="imagetools_reset">Reset</string>
<string name="imagetools_original">Original</string>
<string name="imagetools_result">Result</string>
<string name="imagetools_processing">Processing…</string>
<string name="imagetools_failed">Failed: %s</string>
<string name="imagetools_saved">Saved %s</string>
<string name="imagetools_open">Image tools</string>
<string name="imagetools_view">View</string>
<string name="imagetools_loading">Loading image…</string>
</resources>