feat: new zoom controller

This commit is contained in:
Hinnka committed 2026-01-02 23:32:14 +08:00
1 parent 7776e83608
commit edea3b44ae
7 files changed
+194 -366

No files matched your search

@@ -333,6 +333,8 @@ class Camera2Controller(private val context: Context) {
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to start preview", e)
} catch (e: IllegalStateException) {
Log.e(TAG, "Failed to start preview - illegal state", e)
}
}
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.camera
import android.util.Log
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
@@ -27,8 +28,8 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import com.hinnka.mycamera.camera.CameraState
import com.hinnka.mycamera.camera.CameraUtils
import com.hinnka.mycamera.ui.components.GalleryThumbnail
import com.hinnka.mycamera.ui.components.EditControlPanel
import com.hinnka.mycamera.ui.components.GalleryThumbnail
import com.hinnka.mycamera.ui.components.HistogramView
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.viewmodel.CameraViewModel
@@ -163,10 +164,11 @@ fun CameraScreen(
// Zoom Control Bar (Overlay at bottom of preview)
ZoomControlBar(
zoomRatio = state.zoomRatio,
maxZoom = state.getMaxZoom(),
minZoom = state.getMinZoom(),
zoomRatio = viewModel.zoomRatioByMain,
availableCameras = state.availableCameras,
currentCameraId = state.getCurrentCameraInfo()?.cameraId ?: "0",
onZoomChange = { viewModel.setZoomRatio(it) },
onLensSwitch = { lenId -> viewModel.switchToLens(lenId) },
onFilterClick = {
// Toggle Filter Panel
activePanel = if (activePanel == ActivePanel.FILTERS) ActivePanel.NONE else ActivePanel.FILTERS
@@ -1,44 +1,62 @@
package com.hinnka.mycamera.ui.camera
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.camera.CameraInfo
import com.hinnka.mycamera.camera.LensType
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* 显示模式:变焦倍率 or 35mm等效焦距
*/
enum class ZoomDisplayMode {
ZOOM_RATIO, // 显示 0.6x, 1x, 2x 等
FOCAL_LENGTH // 显示 35mm, 50mm, 85mm 等
}
@Composable
fun ZoomControlBar(
zoomRatio: Float,
maxZoom: Float,
minZoom: Float,
availableCameras: List<CameraInfo>,
currentCameraId: String,
onZoomChange: (Float) -> Unit,
onZoomStop: () -> Unit = {},
onLensSwitch: (String) -> Unit,
onFilterClick: () -> Unit,
modifier: Modifier = Modifier
) {
// 显示模式状态
var displayMode by remember { mutableStateOf(ZoomDisplayMode.FOCAL_LENGTH) }
val currentCameraIdState by rememberUpdatedState(currentCameraId)
val currentCamera = availableCameras.find { it.cameraId == currentCameraId }
// 获取当前相机信息
val mainCamera = availableCameras.find { it.lensType == if (currentCamera?.lensType == LensType.FRONT) LensType.FRONT else LensType.BACK_MAIN }
// 根据可用相机计算变焦档位
val zoomStops = calculateZoomStops(availableCameras, currentCamera)
Box(
modifier = modifier
.fillMaxWidth()
@@ -46,7 +64,30 @@ fun ZoomControlBar(
.height(32.dp),
contentAlignment = Alignment.Center
) {
// Filter Button (Right aligned)
// Display Mode Toggle (Left)
IconButton(
onClick = {
displayMode = if (displayMode == ZoomDisplayMode.ZOOM_RATIO) {
ZoomDisplayMode.FOCAL_LENGTH
} else {
ZoomDisplayMode.ZOOM_RATIO
}
},
modifier = Modifier
.align(Alignment.CenterStart)
.size(32.dp)
) {
Icon(
imageVector = Icons.Default.SwapHoriz,
contentDescription = "Toggle Display Mode",
modifier = Modifier.size(32.dp)
.background(Color.Black.copy(alpha = 0.3f), CircleShape)
.padding(8.dp),
tint = Color.White
)
}
// Filter Button (Right)
IconButton(
onClick = onFilterClick,
modifier = Modifier
@@ -64,69 +105,147 @@ fun ZoomControlBar(
}
// Zoom Ruler (Center)
// We define a fixed set of zoom stops for simplicity, similar to the image: 0.6, 1x, 2, 3, 10
val stops = listOf(0.6f, 1f, 2f, 3f, 5f, 10f).filter { it <= maxZoom && it >= minZoom }
ZoomRuler(
zoomRatio = zoomRatio,
stops = stops,
onZoomChange = onZoomChange,
modifier = Modifier
.fillMaxWidth(0.7f) // Leave room for filter button
.fillMaxHeight()
stops = zoomStops,
mainCamera = mainCamera,
displayMode = displayMode,
onZoomChange = { newZoom ->
// 检查是否需要切换镜头
val camera = findOptimalLens(newZoom, availableCameras, currentCameraIdState)
if (camera != null && camera.cameraId != currentCameraIdState) {
onLensSwitch(camera.cameraId)
}
onZoomChange(newZoom)
},
modifier = Modifier.fillMaxHeight()
)
}
}
/**
* 计算变焦档位
*/
private fun calculateZoomStops(
cameras: List<CameraInfo>,
currentCamera: CameraInfo?
): List<Float> {
val stops = mutableSetOf<Float>()
if (currentCamera?.lensType == LensType.FRONT) {
// 添加各个镜头的固有变焦比例
cameras.filter { it.lensType == LensType.FRONT }.forEach { camera ->
if (camera.intrinsicZoomRatio > 0) {
stops.add(camera.intrinsicZoomRatio)
}
}
stops.add(2f)
return stops.sorted()
}
// 添加各个镜头的固有变焦比例
cameras.filter { it.lensType != LensType.FRONT }.forEach { camera ->
if (camera.intrinsicZoomRatio > 0) {
stops.add(camera.intrinsicZoomRatio)
}
}
val mainCamera = cameras.find { it.lensType == LensType.BACK_MAIN } ?: return stops.sorted()
stops.add(35f / mainCamera.focalLength35mmEquivalent)
stops.add(50f / mainCamera.focalLength35mmEquivalent)
stops.add(85f / mainCamera.focalLength35mmEquivalent)
stops.add(200f / mainCamera.focalLength35mmEquivalent)
return stops.sorted()
}
/**
* 根据变焦倍率找到最佳镜头
*/
private fun findOptimalLens(
targetZoom: Float,
cameras: List<CameraInfo>,
currentCameraId: String
): CameraInfo? {
val currentLensType = cameras.find { it.cameraId == currentCameraId }?.lensType
val zoomableCameras = cameras.filter { if (currentLensType == LensType.FRONT) it.lensType == LensType.FRONT else it.lensType != LensType.FRONT }
if (zoomableCameras.isEmpty()) return null
return zoomableCameras.filter { it.intrinsicZoomRatio <= targetZoom }.sortedByDescending { it.intrinsicZoomRatio }.getOrNull(0)
}
@Composable
fun ZoomRuler(
zoomRatio: Float,
stops: List<Float>,
mainCamera: CameraInfo?,
displayMode: ZoomDisplayMode,
onZoomChange: (Float) -> Unit,
modifier: Modifier = Modifier
) {
val textMeasurer = rememberTextMeasurer()
val activeColor = Color(0xFFFFD700)
val inactiveColor = Color.White.copy(alpha = 0.5f)
Canvas(
val stopsState by rememberUpdatedState(stops)
Row(
modifier = modifier
.background(Color.Black.copy(alpha = 0.3f), RoundedCornerShape(20.dp))
.background(Color.Black.copy(alpha = 0.3f), RoundedCornerShape(16.dp))
.pointerInput(Unit) {
detectTapGestures { offset ->
// Simple tap to nearest stop logic could be added here
// For now, let's just use drag
val width = size.width
val stepWidth = width / stops.size
val index = (offset.x / stepWidth).toInt().coerceIn(0, stops.lastIndex)
onZoomChange(stops[index])
}
}
detectTapGestures { offset ->
val width = size.width
val stepWidth = width / stopsState.size
val index = (offset.x / stepWidth).toInt().coerceIn(0, stopsState.lastIndex)
onZoomChange(stopsState[index])
}
},
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
val width = size.width
val height = size.height
val stepWidth = width / stops.size
stops.forEachIndexed { index, stop ->
val isSelected = abs(stop - zoomRatio) < 0.1f
val x = stepWidth * index + stepWidth / 2
// Draw text
val text = "${stop}x".replace(".0x", "x")
stops.forEachIndexed { _, stop ->
val isSelected = abs(stop - zoomRatio) <= 0.1f
// 显示文本
val text = when (displayMode) {
ZoomDisplayMode.ZOOM_RATIO -> {
formatZoomRatio(stop)
}
ZoomDisplayMode.FOCAL_LENGTH -> {
zoomRatioToFocalLength(stop, mainCamera)
}
}
val style = TextStyle(
fontSize = if (isSelected) 13.sp else 9.sp,
fontSize = if (isSelected) 13.sp else 10.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) activeColor else inactiveColor
)
val textLayoutResult = textMeasurer.measure(text, style)
val textWidth = textLayoutResult.size.width
val textHeight = textLayoutResult.size.height
drawText(
textLayoutResult = textLayoutResult,
topLeft = Offset(x - textWidth / 2, height / 2 - textHeight / 2)
Text(text, style = style, modifier = Modifier
.padding(horizontal = 8.dp)
)
}
}
}
/**
* 格式化变焦倍率显示
*/
private fun formatZoomRatio(ratio: Float): String {
val rounded = (ratio * 10).roundToInt() / 10f
return if (rounded == rounded.toInt().toFloat()) {
"${ratio.toInt()}x"
} else {
String.format("%.1fx", rounded)
}
}
/**
* 变焦倍率转换为35mm等效焦距
*/
private fun zoomRatioToFocalLength(zoomRatio: Float, mainCamera: CameraInfo?): String {
if (mainCamera == null || mainCamera.focalLength35mmEquivalent <= 0) {
// 默认主摄为23mm等效
return (23f * zoomRatio).toInt().toString()
}
return (mainCamera.focalLength35mmEquivalent * zoomRatio).roundToInt().toString()
}
@@ -1,137 +0,0 @@
package com.hinnka.mycamera.ui.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.camera.CameraInfo
import com.hinnka.mycamera.camera.LensType
/**
* 后置摄像头选择器
* 显示可用的后置摄像头(广角、主摄、长焦)供用户切换
*/
@Composable
fun BackCameraSelector(
backCameras: List<CameraInfo>,
currentLensType: LensType,
onLensSelected: (LensType) -> Unit,
modifier: Modifier = Modifier
) {
// 如果后置摄像头少于2个,不显示选择器
if (backCameras.size < 2) return
// 按镜头类型排序
val sortedCameras = backCameras.sortedBy { camera ->
when (camera.lensType) {
LensType.BACK_ULTRA_WIDE -> 0
LensType.BACK_MAIN -> 1
LensType.BACK_TELEPHOTO -> 2
else -> 3
}
}
Row(
modifier = modifier
.background(
Color.Black.copy(alpha = 0.5f),
RoundedCornerShape(24.dp)
)
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(2.dp),
verticalAlignment = Alignment.CenterVertically
) {
sortedCameras.forEach { camera ->
LensButton(
camera = camera,
isSelected = camera.lensType == currentLensType,
onClick = { onLensSelected(camera.lensType) }
)
}
}
}
/**
* 单个镜头按钮
*/
@Composable
private fun LensButton(
camera: CameraInfo,
isSelected: Boolean,
onClick: () -> Unit
) {
val backgroundColor by animateColorAsState(
targetValue = if (isSelected) Color.White else Color.Transparent,
label = "lensBg"
)
val textColor by animateColorAsState(
targetValue = if (isSelected) Color.Black else Color.White,
label = "lensText"
)
val scale by animateFloatAsState(
targetValue = if (isSelected) 1.1f else 1f,
animationSpec = spring(dampingRatio = 0.6f),
label = "lensScale"
)
Box(
modifier = Modifier
.scale(scale)
.clip(RoundedCornerShape(20.dp))
.background(backgroundColor)
.clickable { onClick() }
.padding(horizontal = 12.dp, vertical = 8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = getLensLabel(camera),
color = textColor,
fontSize = 13.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
)
}
}
/**
* 获取镜头显示标签
*/
private fun getLensLabel(camera: CameraInfo): String {
return when (camera.lensType) {
LensType.BACK_ULTRA_WIDE -> {
// 根据 intrinsicZoomRatio 显示
val ratio = camera.intrinsicZoomRatio
if (ratio > 0 && ratio < 1) {
".${(ratio * 10).toInt()}x"
} else {
".5x"
}
}
LensType.BACK_MAIN -> "1x"
LensType.BACK_TELEPHOTO -> {
// 根据 intrinsicZoomRatio 显示
val ratio = camera.intrinsicZoomRatio
if (ratio > 1) {
"${ratio.toInt()}x"
} else {
"2x"
}
}
LensType.FRONT -> "前置"
}
}
@@ -1,129 +0,0 @@
package com.hinnka.mycamera.ui.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* 变焦档位选择器组件
* 显示可用的变焦档位(如 0.5x, 1x, 2x)供用户选择
* 通过变焦来切换广角/主摄/长焦
*/
@Composable
fun ZoomStepSelector(
zoomSteps: List<Float>,
currentZoom: Float,
onZoomSelected: (Float) -> Unit,
modifier: Modifier = Modifier
) {
// 如果没有多个档位,不显示
if (zoomSteps.size <= 1) return
Row(
modifier = modifier
.background(
Color.Black.copy(alpha = 0.5f),
RoundedCornerShape(24.dp)
)
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(2.dp),
verticalAlignment = Alignment.CenterVertically
) {
zoomSteps.forEach { step ->
ZoomStepButton(
step = step,
isSelected = isZoomStepSelected(currentZoom, step, zoomSteps),
onClick = { onZoomSelected(step) }
)
}
}
}
/**
* 判断当前变焦是否选中了某个档位
*/
private fun isZoomStepSelected(currentZoom: Float, step: Float, allSteps: List<Float>): Boolean {
// 找到最接近当前变焦的档位
val closestStep = allSteps.minByOrNull { kotlin.math.abs(it - currentZoom) } ?: return false
return kotlin.math.abs(step - closestStep) < 0.01f
}
/**
* 单个变焦档位按钮
*/
@Composable
private fun ZoomStepButton(
step: Float,
isSelected: Boolean,
onClick: () -> Unit
) {
val backgroundColor by animateColorAsState(
targetValue = if (isSelected) Color.White else Color.Transparent,
label = "zoomStepBg"
)
val textColor by animateColorAsState(
targetValue = if (isSelected) Color.Black else Color.White,
label = "zoomStepText"
)
val scale by animateFloatAsState(
targetValue = if (isSelected) 1.1f else 1f,
animationSpec = spring(dampingRatio = 0.6f),
label = "zoomStepScale"
)
Box(
modifier = Modifier
.scale(scale)
.clip(RoundedCornerShape(20.dp))
.background(backgroundColor)
.clickable { onClick() }
.padding(horizontal = 12.dp, vertical = 8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = formatZoomStep(step),
color = textColor,
fontSize = 13.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
)
}
}
/**
* 格式化变焦档位显示
*/
private fun formatZoomStep(step: Float): String {
return when {
step < 1f -> ".${(step * 10).toInt()}x" // 0.5x -> ".5x"
step == step.toInt().toFloat() -> "${step.toInt()}x" // 2.0 -> "2x"
else -> "${String.format("%.1f", step)}x" // 1.5 -> "1.5x"
}
}
// 保留旧的 LensSelector 作为别名以保持兼容
@Composable
fun LensSelector(
backCameras: List<com.hinnka.mycamera.camera.CameraInfo>,
currentLensType: com.hinnka.mycamera.camera.LensType,
onLensSelected: (com.hinnka.mycamera.camera.LensType) -> Unit,
modifier: Modifier = Modifier
) {
// 此函数保留用于兼容,但不再显示
// 请使用 ZoomStepSelector 替代
}
@@ -6,6 +6,7 @@ import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraMetadata
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
@@ -84,6 +85,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
var availableFrameList: List<FrameInfo> by mutableStateOf(emptyList())
private set
var zoomRatioByMain by mutableFloatStateOf(1f)
// 保存当前的 SurfaceTexture 以便切换摄像头时重用
private var currentSurfaceTexture: SurfaceTexture? = null
@@ -180,45 +183,17 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun switchCamera() {
cameraController.switchCamera()
reopenCamera()
zoomRatioByMain = 1f
}
/**
* 切换到指定的镜头类型
*/
fun switchToLens(lensType: LensType) {
cameraController.switchToLens(lensType)
fun switchToLens(cameraId: String) {
cameraController.switchToCameraId(cameraId)
reopenCamera()
}
/**
* 切换到下一个后置摄像头
*/
fun switchBackCamera() {
val backCameras = getBackCameras().sortedBy {
when (it.lensType) {
LensType.BACK_ULTRA_WIDE -> 0
LensType.BACK_MAIN -> 1
LensType.BACK_TELEPHOTO -> 2
else -> 3
}
}
if (backCameras.isEmpty()) return
val currentLensType = state.value.currentLensType
if (currentLensType == LensType.FRONT) {
switchToLens(LensType.BACK_MAIN)
return
}
val currentIndex = backCameras.indexOfFirst { it.lensType == currentLensType }
val nextIndex = (currentIndex + 1) % backCameras.size
val nextCamera = backCameras[nextIndex]
switchToLens(nextCamera.lensType)
}
/**
* 重新打开相机(切换摄像头后使用)
*/
@@ -267,22 +242,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
* 设置变焦倍数
*/
fun setZoomRatio(ratio: Float) {
cameraController.setZoomRatio(ratio)
}
/**
* 设置到指定的变焦档位
*/
fun setZoomStep(step: Float) {
setZoomRatio(step)
}
/**
* 获取变焦档位列表
* Camera2 不支持通过变焦切换物理摄像头,返回空列表
*/
fun getZoomSteps(): List<Float> {
return emptyList()
zoomRatioByMain = ratio
val cameraInfo = state.value.getCurrentCameraInfo()
val intrinsicZoomRatio = cameraInfo?.intrinsicZoomRatio ?: 1.0f
cameraController.setZoomRatio(ratio / intrinsicZoomRatio)
}
/**
+8
View File
@@ -0,0 +1,8 @@
# 变焦与镜头切换
把变焦和镜头切换功能相融合在一起,可以让用户在使用摄像头时更加灵活和便捷。以下是一些实现这一功能的建议:
1. **多级变焦**:为摄像头设置多个变焦级别(如1x, 2x, 4x等),用户可以通过按钮来选择不同的变焦级别。
2. 在用户切换变焦级别时,自动切换到相应的镜头(如广角镜头、标准镜头、长焦镜头等),以确保图像质量和视野的最佳效果。
3. **平滑过渡**:在变焦和镜头切换过程中,实现平滑的过渡效果,避免突兀的画面变化,提升用户体验
4. 支持在变焦级别和35mm等效焦距之间进行切换,方便用户根据需求选择合适的视角。
5. 页面上始终提供35mm,50mm,85mm等常用焦距的快捷按钮,方便用户快速切换。