commit 25a2e2cb7d494442a87ec3b3ff81a6acbe4a9f5d Author: zhoubinjia Date: Tue Dec 30 15:20:11 2025 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..878c2cd5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle +/local.properties +.idea +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 00000000..3b49719e --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,9 @@ +# Camera App + +这是一个 Android 相机 App,专注于静态摄影,模拟现代数码无反相机的操作手感 + +## 技术框架 + +* UI: Jetpack Compose +* 使用 Camera2 API, 不做向下兼容 +* minSdk 29 \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 00000000..42afabfd --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 00000000..4dfb982c --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,63 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) +} + +android { + namespace = "com.hinnka.mycamera" + compileSdk = 36 + + defaultConfig { + applicationId = "com.hinnka.mycamera" + minSdk = 29 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } + buildFeatures { + compose = true + } +} + +dependencies { + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.activity.compose) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.ui) + implementation(libs.androidx.ui.graphics) + implementation(libs.androidx.ui.tooling.preview) + implementation(libs.androidx.material3) + + // ViewModel Compose + implementation(libs.androidx.lifecycle.viewmodel.compose) + + // Material Icons Extended + implementation(libs.androidx.material.icons.extended) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.ui.test.junit4) + debugImplementation(libs.androidx.ui.tooling) + debugImplementation(libs.androidx.ui.test.manifest) +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 00000000..481bb434 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/com/hinnka/mycamera/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/hinnka/mycamera/ExampleInstrumentedTest.kt new file mode 100644 index 00000000..58e9f9ce --- /dev/null +++ b/app/src/androidTest/java/com/hinnka/mycamera/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.hinnka.mycamera + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.hinnka.mycamera", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..ff7354c2 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/hinnka/mycamera/MainActivity.kt b/app/src/main/java/com/hinnka/mycamera/MainActivity.kt new file mode 100644 index 00000000..7538f79c --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/MainActivity.kt @@ -0,0 +1,135 @@ +package com.hinnka.mycamera + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Bundle +import android.util.Log +import android.view.OrientationEventListener +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import com.hinnka.mycamera.ui.camera.CameraScreen +import com.hinnka.mycamera.ui.theme.PhotonCameraTheme +import com.hinnka.mycamera.viewmodel.CameraViewModel + + +class MainActivity : ComponentActivity() { + + private val viewModel: CameraViewModel by viewModels() + + private var hasCameraPermission by mutableStateOf(false) + + private val permissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestPermission() + ) { isGranted -> + hasCameraPermission = isGranted + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // 启用全屏模式 + enableEdgeToEdge() + hideSystemUI() + orientationListen(viewModel) + + // 检查相机权限 + hasCameraPermission = ContextCompat.checkSelfPermission( + this, Manifest.permission.CAMERA + ) == PackageManager.PERMISSION_GRANTED + + setContent { + PhotonCameraTheme { + Surface( + modifier = Modifier.fillMaxSize(), + color = Color.Black + ) { + if (hasCameraPermission) { + CameraScreen(viewModel = viewModel) + } else { + PermissionScreen( + onRequestPermission = { + permissionLauncher.launch(Manifest.permission.CAMERA) + } + ) + } + } + } + } + } + + private fun hideSystemUI() { + WindowCompat.setDecorFitsSystemWindows(window, false) + WindowInsetsControllerCompat(window, window.decorView).let { controller -> + controller.hide(WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + } + } + + fun orientationListen(viewModel: CameraViewModel) { + val orientationListener: OrientationEventListener = object : OrientationEventListener(this) { + override fun onOrientationChanged(orientation: Int) { + // 只在横竖屏切换时才更新状态,避免频繁重组 + viewModel.updateOrientation(orientation) + } + } + orientationListener.enable() + } +} + +@Composable +fun PermissionScreen( + onRequestPermission: () -> Unit, + modifier: Modifier = Modifier +) { + Box( + modifier = modifier + .fillMaxSize() + .background(Color.Black), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(24.dp) + ) { + Text( + text = stringResource(R.string.camera_permission_required), + color = Color.White, + style = MaterialTheme.typography.headlineSmall, + textAlign = TextAlign.Center + ) + + Button( + onClick = onRequestPermission, + colors = ButtonDefaults.buttonColors( + containerColor = Color(0xFFFF6B35) + ) + ) { + Text(text = stringResource(R.string.grant_permission)) + } + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraController.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraController.kt new file mode 100644 index 00000000..171dacca --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraController.kt @@ -0,0 +1,563 @@ +package com.hinnka.mycamera.camera + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.ImageFormat +import android.hardware.camera2.* +import android.hardware.camera2.params.MeteringRectangle +import android.hardware.camera2.params.OutputConfiguration +import android.hardware.camera2.params.SessionConfiguration +import android.media.ImageReader +import android.os.Build +import android.os.Handler +import android.os.HandlerThread +import android.util.Log +import android.view.Surface +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.util.concurrent.Executors + +/** + * Camera2 API 核心控制器 + */ +class CameraController(private val context: Context) { + + companion object { + private const val TAG = "CameraController" + } + + private val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager + + private var cameraDevice: CameraDevice? = null + private var captureSession: CameraCaptureSession? = null + private var previewRequestBuilder: CaptureRequest.Builder? = null + + private var previewSurface: Surface? = null + private var imageReader: ImageReader? = null + + private var backgroundThread: HandlerThread? = null + private var backgroundHandler: Handler? = null + + private val _state = MutableStateFlow(CameraState()) + val state: StateFlow = _state.asStateFlow() + + // 设备旋转角度(由 ViewModel 更新) + private var deviceRotation: Int = 0 + + // 图片拍摄回调 + var onImageCaptured: ((ByteArray) -> Unit)? = null + + /** + * 初始化相机 + */ + fun initialize() { + startBackgroundThread() + val cameras = CameraUtils.getAvailableCameras(context) + val defaultCameraId = CameraUtils.getDefaultBackCameraId(cameras) ?: cameras.firstOrNull()?.cameraId ?: "" + + _state.value = _state.value.copy( + availableCameras = cameras, + currentCameraId = defaultCameraId, + currentLensType = if (cameras.find { it.cameraId == defaultCameraId }?.lensFacing == CameraCharacteristics.LENS_FACING_FRONT) { + LensType.FRONT + } else { + LensType.BACK_MAIN + } + ) + } + + /** + * 打开相机并开始预览 + */ + @SuppressLint("MissingPermission") + fun openCamera(surface: Surface) { + val cameraId = _state.value.currentCameraId + if (cameraId.isEmpty()) { + Log.e(TAG, "No camera available") + return + } + + previewSurface = surface + + // 创建 ImageReader 用于拍照 + val captureSize = CameraUtils.getOptimalCaptureSize( + context, + cameraId, + _state.value.aspectRatio.getValue(true) + ) + imageReader = ImageReader.newInstance( + captureSize.width, + captureSize.height, + ImageFormat.JPEG, + 2 + ).apply { + setOnImageAvailableListener({ reader -> + val image = reader.acquireLatestImage() + image?.let { + val buffer = it.planes[0].buffer + val bytes = ByteArray(buffer.remaining()) + buffer.get(bytes) + onImageCaptured?.invoke(bytes) + it.close() + } + }, backgroundHandler) + } + + try { + cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() { + override fun onOpened(camera: CameraDevice) { + Log.d(TAG, "Camera opened: $cameraId") + cameraDevice = camera + createCaptureSession() + } + + override fun onDisconnected(camera: CameraDevice) { + Log.d(TAG, "Camera disconnected") + camera.close() + cameraDevice = null + } + + override fun onError(camera: CameraDevice, error: Int) { + Log.e(TAG, "Camera error: $error") + camera.close() + cameraDevice = null + } + }, backgroundHandler) + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to open camera", e) + } + } + + /** + * 创建拍摄会话 + */ + private fun createCaptureSession() { + val device = cameraDevice ?: return + val surface = previewSurface ?: return + val reader = imageReader ?: return + + try { + previewRequestBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply { + addTarget(surface) + // 设置自动对焦 + set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) + // 设置自动曝光 + set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON) + } + + val surfaces = listOf(surface, reader.surface) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + val outputConfigs = surfaces.map { OutputConfiguration(it) } + val sessionConfig = SessionConfiguration( + SessionConfiguration.SESSION_REGULAR, + outputConfigs, + Executors.newSingleThreadExecutor(), + object : CameraCaptureSession.StateCallback() { + override fun onConfigured(session: CameraCaptureSession) { + captureSession = session + startPreview() + } + + override fun onConfigureFailed(session: CameraCaptureSession) { + Log.e(TAG, "Session configuration failed") + } + } + ) + device.createCaptureSession(sessionConfig) + } else { + @Suppress("DEPRECATION") + device.createCaptureSession(surfaces, object : CameraCaptureSession.StateCallback() { + override fun onConfigured(session: CameraCaptureSession) { + captureSession = session + startPreview() + } + + override fun onConfigureFailed(session: CameraCaptureSession) { + Log.e(TAG, "Session configuration failed") + } + }, backgroundHandler) + } + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to create capture session", e) + } + } + + /** + * 开始预览 + */ + private fun startPreview() { + val session = captureSession ?: return + val builder = previewRequestBuilder ?: return + + try { + applySettings(builder) + session.setRepeatingRequest(builder.build(), null, backgroundHandler) + _state.value = _state.value.copy(isPreviewActive = true) + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to start preview", e) + } catch (e: IllegalStateException) { + Log.e(TAG, "Failed to start preview", e) + checkAndRecoverCamera() + } + } + + /** + * 应用当前设置到请求构建器 + */ + private fun applySettings(builder: CaptureRequest.Builder) { + val state = _state.value + val cameraInfo = state.getCurrentCameraInfo() ?: return + + // 曝光补偿 + builder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, state.exposureCompensation) + + // 手动曝光 + if (!state.isAutoExposure) { + builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF) + builder.set(CaptureRequest.SENSOR_SENSITIVITY, state.iso) + builder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, state.shutterSpeed) + } else { + builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON) + } + + // 变焦 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + builder.set(CaptureRequest.CONTROL_ZOOM_RATIO, state.zoomRatio) + } else { + cameraInfo.activeArraySize?.let { arraySize -> + val cropRegion = CameraUtils.calculateCropRegion(arraySize, state.zoomRatio) + builder.set(CaptureRequest.SCALER_CROP_REGION, cropRegion) + } + } + } + + /** + * 更新预览设置 + */ + private fun updatePreview() { + val session = captureSession ?: return + val builder = previewRequestBuilder ?: return + + try { + applySettings(builder) + session.setRepeatingRequest(builder.build(), null, backgroundHandler) + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to update preview", e) + } + } + + /** + * 设置曝光补偿 + */ + fun setExposureCompensation(value: Int) { + val range = _state.value.getExposureCompensationRange() + val clampedValue = value.coerceIn(range.lower, range.upper) + _state.value = _state.value.copy(exposureCompensation = clampedValue) + updatePreview() + } + + /** + * 设置自动曝光模式 + */ + fun setAutoExposure(enabled: Boolean) { + _state.value = _state.value.copy(isAutoExposure = enabled) + updatePreview() + } + + /** + * 设置 ISO + */ + fun setIso(value: Int) { + val range = _state.value.getIsoRange() + val clampedValue = value.coerceIn(range.lower, range.upper) + _state.value = _state.value.copy( + iso = clampedValue, + isAutoExposure = false + ) + updatePreview() + } + + /** + * 设置快门速度 + */ + fun setShutterSpeed(value: Long) { + val range = _state.value.getShutterSpeedRange() + val clampedValue = value.coerceIn(range.lower, range.upper) + _state.value = _state.value.copy( + shutterSpeed = clampedValue, + isAutoExposure = false + ) + updatePreview() + } + + /** + * 设置变焦倍数 + */ + fun setZoomRatio(ratio: Float) { + val maxZoom = _state.value.getMaxZoom() + val clampedRatio = ratio.coerceIn(1f, maxZoom) + _state.value = _state.value.copy(zoomRatio = clampedRatio) + updatePreview() + } + + /** + * 设置画面比例 + */ + fun setAspectRatio(ratio: AspectRatio) { + _state.value = _state.value.copy(aspectRatio = ratio) + } + + /** + * 设置设备旋转角度 + * @param degrees 旋转角度,例如 0, 90, 180, 270 + */ + fun setDeviceRotation(degrees: Int) { + deviceRotation = degrees + } + + /** + * 点击对焦 + */ + fun focusOnPoint(x: Float, y: Float, viewWidth: Int, viewHeight: Int) { + val session = captureSession ?: return + val builder = previewRequestBuilder ?: return + val cameraInfo = _state.value.getCurrentCameraInfo() ?: return + val sensorArraySize = cameraInfo.activeArraySize ?: return + + _state.value = _state.value.copy( + focusPoint = Pair(x / viewWidth, y / viewHeight), + isFocusing = true, + focusSuccess = null + ) + + val isFrontCamera = cameraInfo.lensFacing == CameraCharacteristics.LENS_FACING_FRONT + val focusRegion = CameraUtils.convertTouchToSensorCoordinates( + x, y, viewWidth, viewHeight, + sensorArraySize, + cameraInfo.sensorOrientation, + isFrontCamera + ) + + try { + // 停止连续对焦 + builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO) + builder.set(CaptureRequest.CONTROL_AF_REGIONS, arrayOf(MeteringRectangle(focusRegion, MeteringRectangle.METERING_WEIGHT_MAX))) + builder.set(CaptureRequest.CONTROL_AE_REGIONS, arrayOf(MeteringRectangle(focusRegion, MeteringRectangle.METERING_WEIGHT_MAX))) + + // 触发对焦 + builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START) + + session.capture(builder.build(), object : CameraCaptureSession.CaptureCallback() { + override fun onCaptureCompleted( + session: CameraCaptureSession, + request: CaptureRequest, + result: TotalCaptureResult + ) { + val afState = result.get(CaptureResult.CONTROL_AF_STATE) + val focusSuccess = afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED || + afState == CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED + + _state.value = _state.value.copy( + isFocusing = false, + focusSuccess = focusSuccess + ) + + // 重置为连续对焦 + builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE) + builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) + + try { + session.setRepeatingRequest(builder.build(), null, backgroundHandler) + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to reset focus mode", e) + } + } + }, backgroundHandler) + + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to focus", e) + _state.value = _state.value.copy(isFocusing = false, focusSuccess = false) + } + } + + /** + * 切换摄像头 + */ + fun switchCamera() { + val cameras = _state.value.availableCameras + val currentCameraId = _state.value.currentCameraId + + // 找到下一个摄像头 + val currentCamera = cameras.find { it.cameraId == currentCameraId } + val nextCamera = if (currentCamera?.lensFacing == CameraCharacteristics.LENS_FACING_BACK) { + // 当前是后置,切换到前置 + cameras.find { it.lensFacing == CameraCharacteristics.LENS_FACING_FRONT } + } else { + // 当前是前置,切换到后置 + cameras.find { it.lensFacing == CameraCharacteristics.LENS_FACING_BACK } + } + + nextCamera?.let { camera -> + _state.value = _state.value.copy( + currentCameraId = camera.cameraId, + currentLensType = camera.lensType, + zoomRatio = 1f // 重置变焦 + ) + reopenCamera() + } + } + + /** + * 拍照 + */ + fun capture() { + val device = cameraDevice ?: return + val session = captureSession ?: return + val reader = imageReader ?: return + val cameraInfo = _state.value.getCurrentCameraInfo() ?: return + + _state.value = _state.value.copy(isCapturing = true) + + try { + val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply { + addTarget(reader.surface) + + // 应用相同的设置 + applySettings(this) + + // 设置 JPEG 方向 + val isFrontCamera = cameraInfo.lensFacing == CameraCharacteristics.LENS_FACING_FRONT + val jpegRotation = CameraUtils.computeImageRotation( + cameraInfo.sensorOrientation, + deviceRotation, + isFrontCamera + ) + set(CaptureRequest.JPEG_ORIENTATION, jpegRotation) + + // 使用最高质量 + set(CaptureRequest.JPEG_QUALITY, 95.toByte()) + } + + session.stopRepeating() + session.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() { + override fun onCaptureCompleted( + session: CameraCaptureSession, + request: CaptureRequest, + result: TotalCaptureResult + ) { + _state.value = _state.value.copy(isCapturing = false) + startPreview() + } + + override fun onCaptureFailed( + session: CameraCaptureSession, + request: CaptureRequest, + failure: CaptureFailure + ) { + Log.e(TAG, "Capture failed") + _state.value = _state.value.copy(isCapturing = false) + startPreview() + } + }, backgroundHandler) + + } catch (e: CameraAccessException) { + Log.e(TAG, "Failed to capture", e) + _state.value = _state.value.copy(isCapturing = false) + } + } + + /** + * 重新打开相机 + */ + private fun reopenCamera() { + closeCamera() + previewSurface?.let { surface -> + openCamera(surface) + } + } + + /** + * 检查相机状态并在必要时恢复 + * 用于从后台切换回 App 时调用 + */ + fun checkAndRecoverCamera() { + // 检查 CameraDevice 和 CaptureSession 是否有效 + val needRecover = when { + cameraDevice == null -> { + Log.d(TAG, "CameraDevice is null, need to recover") + true + } + captureSession == null -> { + Log.d(TAG, "CaptureSession is null, need to recover") + true + } + !_state.value.isPreviewActive -> { + Log.d(TAG, "Preview is not active, need to recover") + true + } + else -> { + // 尝试发送一个捕获请求来验证 session 是否有效 + try { + previewRequestBuilder?.let { builder -> + captureSession?.capture(builder.build(), null, backgroundHandler) + } + false + } catch (e: CameraAccessException) { + Log.w(TAG, "Session is invalid, need to recover", e) + true + } catch (e: IllegalStateException) { + Log.w(TAG, "Session is in invalid state, need to recover", e) + true + } + } + } + + if (needRecover) { + Log.d(TAG, "Recovering camera...") + reopenCamera() + } + } + + /** + * 关闭相机 + */ + fun closeCamera() { + try { + captureSession?.close() + captureSession = null + cameraDevice?.close() + cameraDevice = null + imageReader?.close() + imageReader = null + _state.value = _state.value.copy(isPreviewActive = false) + } catch (e: Exception) { + Log.e(TAG, "Error closing camera", e) + } + } + + /** + * 释放资源 + */ + fun release() { + closeCamera() + stopBackgroundThread() + } + + private fun startBackgroundThread() { + backgroundThread = HandlerThread("CameraBackground").also { it.start() } + backgroundHandler = Handler(backgroundThread!!.looper) + } + + private fun stopBackgroundThread() { + backgroundThread?.quitSafely() + try { + backgroundThread?.join() + backgroundThread = null + backgroundHandler = null + } catch (e: InterruptedException) { + Log.e(TAG, "Error stopping background thread", e) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt new file mode 100644 index 00000000..141719e2 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -0,0 +1,125 @@ +package com.hinnka.mycamera.camera + +import android.graphics.Rect +import android.util.Range + +/** + * 画面比例枚举 + */ +enum class AspectRatio(val widthRatio: Int, val heightRatio: Int) { + RATIO_3_2(3, 2), + RATIO_4_3(4, 3), + RATIO_16_9(16, 9), + RATIO_1_1(1, 1); + + fun getValue(isLandscape: Boolean): Float { + return if (isLandscape) { + widthRatio.toFloat() / heightRatio + } else { + heightRatio.toFloat() / widthRatio + } + } + + fun getDisplayName(): String { + return "$widthRatio:$heightRatio" + } +} + +/** + * 相机镜头类型 + */ +enum class LensType { + FRONT, + BACK_MAIN, + BACK_ULTRA_WIDE, + BACK_TELEPHOTO +} + +/** + * 相机信息数据类 + */ +data class CameraInfo( + val cameraId: String, + val lensFacing: Int, + val lensType: LensType, + val physicalCameraIds: List, + val isoRange: Range?, + val exposureTimeRange: Range?, + val exposureCompensationRange: Range, + val exposureCompensationStep: Float, + val maxZoom: Float, + val sensorOrientation: Int, + val activeArraySize: Rect? +) + +/** + * 相机状态数据类 + */ +data class CameraState( + // 当前相机 + val currentCameraId: String = "", + val currentLensType: LensType = LensType.BACK_MAIN, + val availableCameras: List = emptyList(), + + // 曝光控制 + val exposureCompensation: Int = 0, + val isAutoExposure: Boolean = true, + val iso: Int = 100, + val shutterSpeed: Long = 1_000_000_000L / 60, // 1/60s in nanoseconds + + // 对焦 + val isAutoFocus: Boolean = true, + val focusPoint: Pair? = null, // normalized coordinates (0-1) + val isFocusing: Boolean = false, + val focusSuccess: Boolean? = null, + + // 变焦 + val zoomRatio: Float = 1.0f, + + // 画面比例 + val aspectRatio: AspectRatio = AspectRatio.RATIO_3_2, + + // 设备方向 + val deviceRotation: Int = 0, // 0, 90, 180, 270 + + // 是否处于预览状态 + val isPreviewActive: Boolean = false, + + // 是否正在拍照 + val isCapturing: Boolean = false +) { + /** + * 获取当前相机信息 + */ + fun getCurrentCameraInfo(): CameraInfo? { + return availableCameras.find { it.cameraId == currentCameraId } + } + + /** + * 获取曝光补偿范围 + */ + fun getExposureCompensationRange(): Range { + return getCurrentCameraInfo()?.exposureCompensationRange ?: Range(0, 0) + } + + /** + * 获取 ISO 范围 + */ + fun getIsoRange(): Range { + return getCurrentCameraInfo()?.isoRange ?: Range(100, 3200) + } + + /** + * 获取快门速度范围 + */ + fun getShutterSpeedRange(): Range { + return getCurrentCameraInfo()?.exposureTimeRange ?: Range(1_000_000L, 1_000_000_000L) + } + + /** + * 获取最大变焦倍数 + */ + fun getMaxZoom(): Float { + return getCurrentCameraInfo()?.maxZoom ?: 1.0f + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt new file mode 100644 index 00000000..95c52e35 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt @@ -0,0 +1,269 @@ +package com.hinnka.mycamera.camera + +import android.content.Context +import android.graphics.ImageFormat +import android.graphics.Point +import android.graphics.Rect +import android.graphics.SurfaceTexture +import android.hardware.camera2.CameraCharacteristics +import android.hardware.camera2.CameraManager +import android.hardware.camera2.params.StreamConfigurationMap +import android.os.Build +import android.util.Size +import android.view.Surface +import android.view.WindowManager +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +/** + * 相机工具类 + */ +object CameraUtils { + + /** + * 获取所有可用相机信息 + */ + fun getAvailableCameras(context: Context): List { + val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager + val cameras = mutableListOf() + + for (cameraId in cameraManager.cameraIdList) { + val characteristics = cameraManager.getCameraCharacteristics(cameraId) + val lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING) ?: continue + + // 获取物理相机 ID 列表 (Android 9+) + val physicalCameraIds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + characteristics.physicalCameraIds.toList() + } else { + emptyList() + } + + // 确定镜头类型 + val lensType = when { + lensFacing == CameraCharacteristics.LENS_FACING_FRONT -> LensType.FRONT + else -> LensType.BACK_MAIN // 默认为主摄 + } + + // ISO 范围 + val isoRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE) + + // 曝光时间范围 + val exposureTimeRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE) + + // 曝光补偿范围 + val exposureCompensationRange = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE) + ?: android.util.Range(0, 0) + + // 曝光补偿步长 + val exposureCompensationStep = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP)?.toFloat() ?: 0f + + // 最大变焦 + val maxZoom = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + characteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE)?.upper ?: 1f + } else { + characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM) ?: 1f + } + + // 传感器方向 + val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 + + // 活动区域大小 + val activeArraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) + + cameras.add( + CameraInfo( + cameraId = cameraId, + lensFacing = lensFacing, + lensType = lensType, + physicalCameraIds = physicalCameraIds, + isoRange = isoRange, + exposureTimeRange = exposureTimeRange, + exposureCompensationRange = exposureCompensationRange, + exposureCompensationStep = exposureCompensationStep, + maxZoom = maxZoom, + sensorOrientation = sensorOrientation, + activeArraySize = activeArraySize + ) + ) + } + + return cameras + } + + /** + * 获取默认后置相机 ID + */ + fun getDefaultBackCameraId(cameras: List): String? { + return cameras.find { + it.lensFacing == CameraCharacteristics.LENS_FACING_BACK + }?.cameraId + } + + /** + * 获取固定的预览尺寸(16:9) + * 使用固定尺寸可以避免切换画面比例时频繁重新配置相机会话, + * 不同的画面比例通过 UI 裁切实现 + */ + fun getFixedPreviewSize( + context: Context, + cameraId: String + ): Size { + val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager + val characteristics = cameraManager.getCameraCharacteristics(cameraId) + val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + ?: return Size(1920, 1080) + + val previewSizes = map.getOutputSizes(SurfaceTexture::class.java)?.toList() ?: emptyList() + + // 目标比例 16:9 + val targetRatio = 16f / 9f + + // 优先选择 1920x1080 + val preferred = previewSizes.find { it.width == 1920 && it.height == 1080 } + if (preferred != null) return preferred + + // 筛选 16:9 比例的尺寸,选择最接近 1080p 的 + val ratio16by9Sizes = previewSizes.filter { size -> + val ratio = size.width.toFloat() / size.height + abs(ratio - targetRatio) < 0.01f + } + + return ratio16by9Sizes + .minByOrNull { abs(it.height - 1080) } + ?: previewSizes.firstOrNull() + ?: Size(1920, 1080) + } + + /** + * 获取最佳拍照尺寸 + */ + fun getOptimalCaptureSize( + context: Context, + cameraId: String, + targetRatio: Float + ): Size { + val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager + val characteristics = cameraManager.getCameraCharacteristics(cameraId) + val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + ?: return Size(4032, 3024) + + val captureSizes = map.getOutputSizes(ImageFormat.JPEG)?.toList() ?: emptyList() + + // 选择最接近目标比例且分辨率最高的尺寸 + return captureSizes +// .filter { size -> +// val ratio = size.width.toFloat() / size.height +// abs(ratio - targetRatio) < 0.1f +// } + .maxByOrNull { it.width * it.height } + ?: captureSizes.firstOrNull() + ?: Size(4032, 3024) + } + + /** + * 计算 JPEG 图片的旋转角度 + */ + fun computeImageRotation(sensorOrientation: Int, deviceRotation: Int, isFrontCamera: Boolean): Int { + return if (isFrontCamera) { + (sensorOrientation + deviceRotation) % 360 + } else { + (sensorOrientation - deviceRotation + 360) % 360 + } + } + + /** + * 计算裁剪区域用于变焦 + */ + fun calculateCropRegion( + activeArraySize: Rect, + zoomRatio: Float + ): Rect { + val centerX = activeArraySize.centerX() + val centerY = activeArraySize.centerY() + + val newWidth = (activeArraySize.width() / zoomRatio).toInt() + val newHeight = (activeArraySize.height() / zoomRatio).toInt() + + val left = centerX - newWidth / 2 + val top = centerY - newHeight / 2 + val right = centerX + newWidth / 2 + val bottom = centerY + newHeight / 2 + + return Rect( + max(0, left), + max(0, top), + min(activeArraySize.right, right), + min(activeArraySize.bottom, bottom) + ) + } + + /** + * 将屏幕触摸点转换为传感器坐标 + */ + fun convertTouchToSensorCoordinates( + touchX: Float, + touchY: Float, + viewWidth: Int, + viewHeight: Int, + sensorArraySize: Rect, + sensorOrientation: Int, + isFrontCamera: Boolean + ): Rect { + // 归一化触摸坐标 + val normalizedX = touchX / viewWidth + val normalizedY = touchY / viewHeight + + // 根据传感器方向转换坐标 + val (sensorX, sensorY) = when (sensorOrientation) { + 90 -> Pair(normalizedY, 1f - normalizedX) + 180 -> Pair(1f - normalizedX, 1f - normalizedY) + 270 -> Pair(1f - normalizedY, normalizedX) + else -> Pair(normalizedX, normalizedY) + } + + // 前置摄像头需要水平翻转 + val finalX = if (isFrontCamera) 1f - sensorX else sensorX + + // 计算对焦区域(约 10% 的传感器面积) + val areaSize = (min(sensorArraySize.width(), sensorArraySize.height()) * 0.1f).toInt() + + val centerX = (sensorArraySize.left + finalX * sensorArraySize.width()).toInt() + val centerY = (sensorArraySize.top + sensorY * sensorArraySize.height()).toInt() + + return Rect( + max(sensorArraySize.left, centerX - areaSize / 2), + max(sensorArraySize.top, centerY - areaSize / 2), + min(sensorArraySize.right, centerX + areaSize / 2), + min(sensorArraySize.bottom, centerY + areaSize / 2) + ) + } + + /** + * 格式化快门速度显示 + */ + fun formatShutterSpeed(exposureTimeNanos: Long): String { + return when { + exposureTimeNanos >= 1_000_000_000L -> { + val seconds = exposureTimeNanos / 1_000_000_000.0 + String.format("%.1f\"", seconds) + } + else -> { + val fraction = (1_000_000_000.0 / exposureTimeNanos).toInt() + "1/$fraction" + } + } + } + + /** + * 格式化曝光补偿显示 + */ + fun formatExposureCompensation(value: Int, step: Float): String { + val ev = value * step + return when { + ev > 0 -> "+${String.format("%.1f", ev)}" + ev < 0 -> String.format("%.1f", ev) + else -> "0" + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreview.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreview.kt new file mode 100644 index 00000000..93c6d802 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreview.kt @@ -0,0 +1,188 @@ +package com.hinnka.mycamera.ui.camera + +import android.graphics.Matrix +import android.graphics.SurfaceTexture +import android.util.Size +import android.view.Surface +import android.view.TextureView +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.viewinterop.AndroidView +import com.hinnka.mycamera.camera.AspectRatio +import com.hinnka.mycamera.ui.components.FocusIndicator + +/** + * 相机预览组件 + */ +@Composable +fun CameraPreview( + aspectRatio: AspectRatio, + previewSize: Size, + focusPoint: Pair?, + isFocusing: Boolean, + focusSuccess: Boolean?, + onSurfaceReady: (Surface) -> Unit, + onSurfaceDestroyed: () -> Unit, + onTap: (Float, Float, Int, Int) -> Unit, + modifier: Modifier = Modifier +) { + + // 计算预览区域尺寸,保持目标比例 + BoxWithConstraints( + modifier = modifier + .fillMaxSize() + .background(Color.Black), + contentAlignment = Alignment.Center + ) { + val containerWidth = constraints.maxWidth.toFloat() + val containerHeight = constraints.maxHeight.toFloat() + + // 目标显示比例 + val targetRatio = aspectRatio.getValue(false) + + // 计算裁切后的显示区域大小 + val displayWidth: Float + val displayHeight: Float + + if (containerWidth / containerHeight > targetRatio) { + // 容器更宽,以高度为基准 + displayHeight = containerHeight + displayWidth = displayHeight * targetRatio + } else { + // 容器更高,以宽度为基准 + displayWidth = containerWidth + displayHeight = displayWidth / targetRatio + } + + var viewWidth by remember { mutableIntStateOf(0) } + var viewHeight by remember { mutableIntStateOf(0) } + + var previewSizeState by remember { mutableStateOf(previewSize) } + + Box( + modifier = Modifier + .width(with(LocalDensity.current) { displayWidth.toDp() }) + .height(with(LocalDensity.current) { displayHeight.toDp() }) + .clipToBounds() // 裁切超出部分 + .pointerInput(Unit) { + detectTapGestures { offset -> + onTap(offset.x, offset.y, viewWidth, viewHeight) + } + } + ) { + // TextureView 用于相机预览 + AndroidView( + factory = { ctx -> + TextureView(ctx).apply { + surfaceTextureListener = object : TextureView.SurfaceTextureListener { + override fun onSurfaceTextureAvailable( + surfaceTexture: SurfaceTexture, + width: Int, + height: Int + ) { + viewWidth = width + viewHeight = height + // 设置固定的预览尺寸 + surfaceTexture.setDefaultBufferSize(previewSizeState.width, previewSizeState.height) + // 应用 centerCrop 变换矩阵 + applyCenterCropTransform(this@apply, previewSizeState, width, height) + // 通知相机 Surface 已准备好 + onSurfaceReady(Surface(surfaceTexture)) + } + + override fun onSurfaceTextureSizeChanged( + surfaceTexture: SurfaceTexture, + width: Int, + height: Int + ) { + viewWidth = width + viewHeight = height + surfaceTexture.setDefaultBufferSize(previewSizeState.width, previewSizeState.height) + // 只更新变换矩阵,不重新配置相机 + applyCenterCropTransform(this@apply, previewSizeState, width, height) + } + + override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean { + onSurfaceDestroyed() + return true + } + + override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) { + // 不需要处理 + } + } + } + }, + update = { textureView -> + // 当显示区域尺寸变化时(比例切换),只更新变换矩阵 + if (textureView.width > 0 && textureView.height > 0) { + previewSizeState = previewSize + } + }, + modifier = Modifier.fillMaxSize() + ) + + // 对焦指示器 + FocusIndicator( + position = focusPoint, + isFocusing = isFocusing, + focusSuccess = focusSuccess, + modifier = Modifier.fillMaxSize() + ) + } + } +} + +/** + * 应用 centerCrop 变换矩阵 + * 当预览尺寸与显示区域比例不匹配时,放大画面并裁切超出部分 + */ +private fun applyCenterCropTransform( + textureView: TextureView, + previewSize: Size, + viewWidth: Int, + viewHeight: Int +) { + if (viewWidth == 0 || viewHeight == 0) return + + // 预览尺寸是横向的(如 1920x1080),但显示区域是竖向的 + // 相机预览会自动旋转,所以这里需要交换预览的宽高来计算比例 + val previewWidth = previewSize.height.toFloat() + val previewHeight = previewSize.width.toFloat() + + val viewRatio = viewWidth.toFloat() / viewHeight + val previewRatio = previewWidth / previewHeight + + val matrix = Matrix() + + if (previewRatio != viewRatio) { + val scaleX: Float + val scaleY: Float + + if (viewRatio > previewRatio) { + // 显示区域更宽,需要基于宽度缩放,裁切上下 + scaleX = 1f + scaleY = viewRatio / previewRatio + } else { + // 显示区域更高,需要基于高度缩放,裁切左右 + scaleX = previewRatio / viewRatio + scaleY = 1f + } + + // 以中心点进行缩放 + val pivotX = viewWidth / 2f + val pivotY = viewHeight / 2f + matrix.setScale(scaleX, scaleY, pivotX, pivotY) + } + + textureView.setTransform(matrix) +} + diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt new file mode 100644 index 00000000..a59616c6 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -0,0 +1,386 @@ +package com.hinnka.mycamera.ui.camera + +import android.util.Log +import android.view.Surface +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.spring +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Cameraswitch +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +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.rotate +import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.layout +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import com.hinnka.mycamera.camera.CameraState +import com.hinnka.mycamera.viewmodel.CameraViewModel +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.sin + +/** + * 主相机界面 + */ +@Composable +fun CameraScreen( + viewModel: CameraViewModel, + modifier: Modifier = Modifier +) { + val state by viewModel.state.collectAsState() + + var surface by remember { mutableStateOf(null) } + + // 当 surface 准备好时打开相机 + LaunchedEffect(surface) { + surface?.let { + viewModel.openCamera(it) + } + } + + // 从后台返回时检查并恢复相机 + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + // 只有在 surface 已经存在时才检查恢复 + if (surface != null) { + viewModel.checkAndRecoverCamera() + } + } + + Box( + modifier = modifier + .fillMaxSize() + .background(Color.Black) + ) { + // 相机预览 + CameraPreview( + aspectRatio = state.aspectRatio, + previewSize = viewModel.getPreviewSize(), + focusPoint = state.focusPoint, + isFocusing = state.isFocusing, + focusSuccess = state.focusSuccess, + onSurfaceReady = { surface = it }, + onSurfaceDestroyed = { + viewModel.closeCamera() + surface = null + }, + onTap = { x, y, w, h -> + viewModel.focusOnPoint(x, y, w, h) + }, + modifier = Modifier.fillMaxSize() + ) + + // 控制层 + Controls(state, viewModel) + } +} + +@Composable +fun Controls( + state: CameraState, + viewModel: CameraViewModel +) { + var showControlPanel by remember { mutableStateOf(true) } + + if (viewModel.isLandscape) { + // 旋转整个UI布局 + Box( + modifier = Modifier + .fillMaxSize() + .rotateWithLayout(360 - viewModel.rotationDegrees), + contentAlignment = Alignment.Center + ) { + LandscapeControlsContent( + state = state, + showControlPanel = showControlPanel, + onToggleControlPanel = { showControlPanel = !showControlPanel }, + onCapture = { viewModel.capture() }, + onSwitchCamera = { viewModel.switchCamera() }, + onExposureCompensationChange = { viewModel.setExposureCompensation(it) }, + onIsoChange = { viewModel.setIso(it) }, + onShutterSpeedChange = { viewModel.setShutterSpeed(it) }, + onZoomChange = { viewModel.setZoomRatio(it) }, + onAspectRatioChange = { viewModel.setAspectRatio(it) }, + onAutoExposureToggle = { viewModel.setAutoExposure(it) } + ) + } + } else { + PortraitControls( + state = state, + showControlPanel = showControlPanel, + onToggleControlPanel = { showControlPanel = !showControlPanel }, + onCapture = { viewModel.capture() }, + onSwitchCamera = { viewModel.switchCamera() }, + onExposureCompensationChange = { viewModel.setExposureCompensation(it) }, + onIsoChange = { viewModel.setIso(it) }, + onShutterSpeedChange = { viewModel.setShutterSpeed(it) }, + onZoomChange = { viewModel.setZoomRatio(it) }, + onAspectRatioChange = { viewModel.setAspectRatio(it) }, + onAutoExposureToggle = { viewModel.setAutoExposure(it) } + ) + } +} + +fun Modifier.rotateWithLayout(degrees: Float) = this.layout { measurable, constraints -> + // 1. 计算旋转后的外接矩形尺寸需求 + val rad = Math.toRadians(degrees.toDouble()) + val cos = abs(cos(rad)) + val sin = abs(sin(rad)) + + // 2. 根据父约束和旋转角度,反推子组件应该有的尺寸 + // 如果是 90 度,这里会自动交换宽高约束 + val newWidth = (constraints.maxWidth * cos + constraints.maxHeight * sin).toInt() + val newHeight = (constraints.maxWidth * sin + constraints.maxHeight * cos).toInt() + + // 3. 测量子组件 + val placeable = measurable.measure(constraints.copy( + minWidth = 0, + minHeight = 0, + maxWidth = newWidth, + maxHeight = newHeight + )) + + // 4. 这里的 layout 尺寸决定了它在父容器中占多大位子 + layout(newWidth, newHeight) { + placeable.placeRelativeWithLayer( + (newWidth - placeable.width) / 2, + (newHeight - placeable.height) / 2 + ) { + rotationZ = degrees + } + } +} + +/** + * 横屏控制布局内容(用于旋转显示) + */ +@Composable +fun LandscapeControlsContent( + state: CameraState, + showControlPanel: Boolean, + onToggleControlPanel: () -> Unit, + onCapture: () -> Unit, + onSwitchCamera: () -> Unit, + onExposureCompensationChange: (Int) -> Unit, + onIsoChange: (Int) -> Unit, + onShutterSpeedChange: (Long) -> Unit, + onZoomChange: (Float) -> Unit, + onAspectRatioChange: (com.hinnka.mycamera.camera.AspectRatio) -> Unit, + onAutoExposureToggle: (Boolean) -> Unit +) { + // 横屏布局:左侧控制面板,右侧按钮 + // 直接填充父容器,让旋转后的布局自动适应 + Row( + modifier = Modifier.fillMaxSize(), + horizontalArrangement = Arrangement.SpaceBetween + ) { + // 左侧控制面板 + if (showControlPanel) { + Box( + modifier = Modifier + .fillMaxHeight() + .width(200.dp) + ) { + ControlPanel( + state = state, + onExposureCompensationChange = onExposureCompensationChange, + onIsoChange = onIsoChange, + onShutterSpeedChange = onShutterSpeedChange, + onZoomChange = onZoomChange, + onAspectRatioChange = onAspectRatioChange, + onAutoExposureToggle = onAutoExposureToggle, + modifier = Modifier.fillMaxSize() + ) + } + } + + Spacer(modifier = Modifier.weight(1f)) + + // 右侧按钮区 + Column( + modifier = Modifier + .fillMaxHeight() + .padding(16.dp), + verticalArrangement = Arrangement.SpaceEvenly, + horizontalAlignment = Alignment.CenterHorizontally + ) { + // 设置按钮(切换控制面板) + IconButton( + onClick = onToggleControlPanel, + modifier = Modifier + .size(48.dp) + .background( + Color.Black.copy(alpha = 0.5f), + CircleShape + ) + ) { + Icon( + imageVector = Icons.Default.Settings, + contentDescription = "Settings", + tint = Color.White + ) + } + + // 拍照按钮 + CaptureButton( + isCapturing = state.isCapturing, + onClick = onCapture + ) + + // 切换摄像头按钮 + IconButton( + onClick = onSwitchCamera, + modifier = Modifier + .size(48.dp) + .background( + Color.Black.copy(alpha = 0.5f), + CircleShape + ) + ) { + Icon( + imageVector = Icons.Default.Cameraswitch, + contentDescription = "Switch Camera", + tint = Color.White + ) + } + } + } +} + +/** + * 竖屏控制布局 + */ +@Composable +fun PortraitControls( + state: CameraState, + showControlPanel: Boolean, + onToggleControlPanel: () -> Unit, + onCapture: () -> Unit, + onSwitchCamera: () -> Unit, + onExposureCompensationChange: (Int) -> Unit, + onIsoChange: (Int) -> Unit, + onShutterSpeedChange: (Long) -> Unit, + onZoomChange: (Float) -> Unit, + onAspectRatioChange: (com.hinnka.mycamera.camera.AspectRatio) -> Unit, + onAutoExposureToggle: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + Column( + modifier = modifier.fillMaxSize(), + verticalArrangement = Arrangement.SpaceBetween + ) { + // 顶部控制面板 + if (showControlPanel) { + ControlPanel( + state = state, + onExposureCompensationChange = onExposureCompensationChange, + onIsoChange = onIsoChange, + onShutterSpeedChange = onShutterSpeedChange, + onZoomChange = onZoomChange, + onAspectRatioChange = onAspectRatioChange, + onAutoExposureToggle = onAutoExposureToggle + ) + } + + Spacer(modifier = Modifier.weight(1f)) + + // 底部按钮区 + Row( + modifier = Modifier + .fillMaxWidth() + .background(Color.Black.copy(alpha = 0.6f)) + .padding(vertical = 24.dp, horizontal = 32.dp), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically + ) { + // 设置按钮(切换控制面板) + IconButton( + onClick = onToggleControlPanel, + modifier = Modifier + .size(48.dp) + .background( + Color.White.copy(alpha = 0.2f), + CircleShape + ) + ) { + Icon( + imageVector = Icons.Default.Settings, + contentDescription = "Settings", + tint = Color.White + ) + } + + // 拍照按钮 + CaptureButton( + isCapturing = state.isCapturing, + onClick = onCapture + ) + + // 切换摄像头按钮 + IconButton( + onClick = onSwitchCamera, + modifier = Modifier + .size(48.dp) + .background( + Color.White.copy(alpha = 0.2f), + CircleShape + ) + ) { + Icon( + imageVector = Icons.Default.Cameraswitch, + contentDescription = "Switch Camera", + tint = Color.White + ) + } + } + } +} + +/** + * 拍照按钮 + */ +@Composable +fun CaptureButton( + isCapturing: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + val scale by animateFloatAsState( + targetValue = if (isCapturing) 0.9f else 1f, + animationSpec = spring(dampingRatio = 0.5f), + label = "captureScale" + ) + + Box( + modifier = modifier + .size(72.dp) + .scale(scale) + .clip(CircleShape) + .background(Color.White) + .border(4.dp, Color.White.copy(alpha = 0.5f), CircleShape) + .clickable(enabled = !isCapturing) { onClick() } + .padding(4.dp), + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .fillMaxSize() + .clip(CircleShape) + .background( + if (isCapturing) Color.Gray else Color.White + ) + ) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/ControlPanel.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/ControlPanel.kt new file mode 100644 index 00000000..c9d34574 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/ControlPanel.kt @@ -0,0 +1,310 @@ +package com.hinnka.mycamera.ui.camera + +import androidx.compose.animation.* +import androidx.compose.foundation.background +import androidx.compose.foundation.border +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.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.hinnka.mycamera.R +import com.hinnka.mycamera.camera.AspectRatio +import com.hinnka.mycamera.camera.CameraState +import com.hinnka.mycamera.camera.CameraUtils +import com.hinnka.mycamera.ui.components.DialControl + +/** + * 控制面板组件 + */ +@Composable +fun ControlPanel( + state: CameraState, + onExposureCompensationChange: (Int) -> Unit, + onIsoChange: (Int) -> Unit, + onShutterSpeedChange: (Long) -> Unit, + onZoomChange: (Float) -> Unit, + onAspectRatioChange: (AspectRatio) -> Unit, + onAutoExposureToggle: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + var showAspectRatioSelector by remember { mutableStateOf(false) } + var showExposureControls by remember { mutableStateOf(false) } + + val cameraInfo = state.getCurrentCameraInfo() + + Column( + modifier = modifier + .fillMaxWidth() + .background(Color.Black.copy(alpha = 0.6f)) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + // 顶部信息栏 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + // 画面比例按钮 + TextButton( + onClick = { showAspectRatioSelector = !showAspectRatioSelector }, + colors = ButtonDefaults.textButtonColors(contentColor = Color.White) + ) { + Text( + text = state.aspectRatio.getDisplayName(), + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ) + } + + // 变焦指示 + Text( + text = "${String.format("%.1f", state.zoomRatio)}x", + color = Color.White, + fontSize = 14.sp + ) + + // 曝光控制开关 + TextButton( + onClick = { showExposureControls = !showExposureControls }, + colors = ButtonDefaults.textButtonColors(contentColor = Color.White) + ) { + Text( + text = if (state.isAutoExposure) stringResource(R.string.auto) else "M", + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ) + } + } + + // 画面比例选择器 + AnimatedVisibility( + visible = showAspectRatioSelector, + enter = fadeIn() + expandVertically(), + exit = fadeOut() + shrinkVertically() + ) { + AspectRatioSelector( + selected = state.aspectRatio, + onSelect = { + onAspectRatioChange(it) + showAspectRatioSelector = false + } + ) + } + + // 曝光控制 + AnimatedVisibility( + visible = showExposureControls, + enter = fadeIn() + expandVertically(), + exit = fadeOut() + shrinkVertically() + ) { + ExposureControls( + state = state, + onExposureCompensationChange = onExposureCompensationChange, + onIsoChange = onIsoChange, + onShutterSpeedChange = onShutterSpeedChange, + onAutoExposureToggle = onAutoExposureToggle + ) + } + + // 变焦滑块 + ZoomSlider( + value = state.zoomRatio, + maxValue = state.getMaxZoom(), + onValueChange = onZoomChange + ) + } +} + +/** + * 画面比例选择器 + */ +@Composable +fun AspectRatioSelector( + selected: AspectRatio, + onSelect: (AspectRatio) -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceEvenly + ) { + AspectRatio.entries.forEach { ratio -> + val isSelected = ratio == selected + Box( + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .background( + if (isSelected) Color(0xFFFF6B35) else Color.Transparent + ) + .border( + width = 1.dp, + color = if (isSelected) Color.Transparent else Color.White.copy(alpha = 0.5f), + shape = RoundedCornerShape(8.dp) + ) + .clickable { onSelect(ratio) } + .padding(horizontal = 16.dp, vertical = 8.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = ratio.getDisplayName(), + color = Color.White, + fontSize = 12.sp, + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal + ) + } + } + } +} + +/** + * 曝光控制组件 + */ +@Composable +fun ExposureControls( + state: CameraState, + onExposureCompensationChange: (Int) -> Unit, + onIsoChange: (Int) -> Unit, + onShutterSpeedChange: (Long) -> Unit, + onAutoExposureToggle: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + val cameraInfo = state.getCurrentCameraInfo() + val evRange = state.getExposureCompensationRange() + val isoRange = state.getIsoRange() + val shutterRange = state.getShutterSpeedRange() + val evStep = cameraInfo?.exposureCompensationStep ?: 1/3f + + Column( + modifier = modifier.padding(vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // 自动/手动切换 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.auto), + color = Color.White, + fontSize = 12.sp + ) + Spacer(modifier = Modifier.width(8.dp)) + Switch( + checked = !state.isAutoExposure, + onCheckedChange = { onAutoExposureToggle(!it) }, + colors = SwitchDefaults.colors( + checkedThumbColor = Color(0xFFFF6B35), + checkedTrackColor = Color(0xFFFF6B35).copy(alpha = 0.5f) + ) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "M", + color = Color.White, + fontSize = 12.sp + ) + } + + // 旋钮控制区 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceEvenly + ) { + // 曝光补偿 + DialControl( + value = state.exposureCompensation.toFloat(), + onValueChange = { onExposureCompensationChange(it.toInt()) }, + minValue = evRange.lower.toFloat(), + maxValue = evRange.upper.toFloat(), + steps = (evRange.upper - evRange.lower), + label = stringResource(R.string.exposure_compensation), + valueFormatter = { + CameraUtils.formatExposureCompensation(it.toInt(), evStep) + } + ) + + // ISO(仅手动模式) + if (!state.isAutoExposure) { + DialControl( + value = state.iso.toFloat(), + onValueChange = { onIsoChange(it.toInt()) }, + minValue = isoRange.lower.toFloat(), + maxValue = isoRange.upper.toFloat(), + steps = 20, + label = stringResource(R.string.iso), + valueFormatter = { it.toInt().toString() } + ) + + // 快门速度 + DialControl( + value = state.shutterSpeed.toFloat(), + onValueChange = { onShutterSpeedChange(it.toLong()) }, + minValue = shutterRange.lower.toFloat(), + maxValue = shutterRange.upper.toFloat(), + steps = 20, + label = stringResource(R.string.shutter_speed), + valueFormatter = { + CameraUtils.formatShutterSpeed(it.toLong()) + } + ) + } + } + } +} + +/** + * 变焦滑块 + */ +@Composable +fun ZoomSlider( + value: Float, + maxValue: Float, + onValueChange: (Float) -> Unit, + modifier: Modifier = Modifier +) { + Column(modifier = modifier) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.zoom), + color = Color.White.copy(alpha = 0.7f), + fontSize = 10.sp + ) + Text( + text = "${String.format("%.1f", value)}x", + color = Color.White, + fontSize = 12.sp, + fontWeight = FontWeight.Bold + ) + } + + Slider( + value = value, + onValueChange = onValueChange, + valueRange = 1f..maxValue, + colors = SliderDefaults.colors( + thumbColor = Color(0xFFFF6B35), + activeTrackColor = Color(0xFFFF6B35), + inactiveTrackColor = Color.White.copy(alpha = 0.3f) + ), + modifier = Modifier.fillMaxWidth() + ) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/DialControl.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/DialControl.kt new file mode 100644 index 00000000..b05fa0a5 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/DialControl.kt @@ -0,0 +1,294 @@ +package com.hinnka.mycamera.ui.components + +import androidx.compose.animation.core.* +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.* +import androidx.compose.material3.MaterialTheme +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.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.rotate +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlin.math.PI +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin + +/** + * 模拟物理旋钮的控件 + */ +@Composable +fun DialControl( + value: Float, + onValueChange: (Float) -> Unit, + minValue: Float, + maxValue: Float, + steps: Int = 20, + label: String, + valueFormatter: (Float) -> String = { it.toString() }, + modifier: Modifier = Modifier +) { + var rotationAngle by remember { mutableFloatStateOf(0f) } + var lastAngle by remember { mutableFloatStateOf(0f) } + + // 将值映射到角度 (-135° 到 135°) + val valueRange = maxValue - minValue + val normalizedValue = (value - minValue) / valueRange + val targetAngle = -135f + normalizedValue * 270f + + // 动画 + val animatedAngle by animateFloatAsState( + targetValue = targetAngle, + animationSpec = spring(dampingRatio = 0.8f, stiffness = 300f), + label = "dialRotation" + ) + + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = modifier + ) { + // 标签 + Text( + text = label, + color = Color.White.copy(alpha = 0.7f), + fontSize = 10.sp, + fontWeight = FontWeight.Medium + ) + + Spacer(modifier = Modifier.height(4.dp)) + + // 旋钮 + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(80.dp) + .pointerInput(Unit) { + detectDragGestures( + onDragStart = { offset -> + val centerX = size.width / 2f + val centerY = size.height / 2f + lastAngle = atan2( + offset.y - centerY, + offset.x - centerX + ) * (180f / PI.toFloat()) + }, + onDrag = { change, _ -> + change.consume() + val centerX = size.width / 2f + val centerY = size.height / 2f + val currentAngle = atan2( + change.position.y - centerY, + change.position.x - centerX + ) * (180f / PI.toFloat()) + + var delta = currentAngle - lastAngle + // 处理角度跳跃 + if (delta > 180) delta -= 360 + if (delta < -180) delta += 360 + + rotationAngle += delta + lastAngle = currentAngle + + // 将旋转角度映射回值 + val newNormalizedValue = ((rotationAngle + 135f) / 270f).coerceIn(0f, 1f) + val newValue = minValue + newNormalizedValue * valueRange + onValueChange(newValue) + } + ) + } + ) { + // 刻度盘 + Canvas(modifier = Modifier.fillMaxSize()) { + val center = Offset(size.width / 2, size.height / 2) + val outerRadius = size.minDimension / 2 - 4.dp.toPx() + val innerRadius = outerRadius - 8.dp.toPx() + + // 绘制刻度 + for (i in 0..steps) { + val angle = -135f + (i.toFloat() / steps) * 270f + val radian = angle * PI.toFloat() / 180f + + val isMainTick = i % 5 == 0 + val tickLength = if (isMainTick) 6.dp.toPx() else 3.dp.toPx() + val tickWidth = if (isMainTick) 2f else 1f + val tickAlpha = if (isMainTick) 0.8f else 0.4f + + val startRadius = outerRadius - tickLength + val startX = center.x + cos(radian) * startRadius + val startY = center.y + sin(radian) * startRadius + val endX = center.x + cos(radian) * outerRadius + val endY = center.y + sin(radian) * outerRadius + + drawLine( + color = Color.White.copy(alpha = tickAlpha), + start = Offset(startX, startY), + end = Offset(endX, endY), + strokeWidth = tickWidth, + cap = StrokeCap.Round + ) + } + + // 绘制指针 + rotate(animatedAngle) { + val pointerLength = innerRadius - 10.dp.toPx() + drawLine( + color = Color(0xFFFF6B35), + start = center, + end = Offset(center.x, center.y - pointerLength), + strokeWidth = 3.dp.toPx(), + cap = StrokeCap.Round + ) + + // 中心点 + drawCircle( + color = Color.White, + radius = 4.dp.toPx(), + center = center + ) + } + } + } + + Spacer(modifier = Modifier.height(4.dp)) + + // 当前值 + Text( + text = valueFormatter(value), + color = Color.White, + fontSize = 14.sp, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center + ) + } +} + +/** + * 对焦指示器 + */ +@Composable +fun FocusIndicator( + position: Pair?, + isFocusing: Boolean, + focusSuccess: Boolean?, + modifier: Modifier = Modifier +) { + if (position == null) return + + val infiniteTransition = rememberInfiniteTransition(label = "focusAnimation") + + // 聚焦动画 + val scale by infiniteTransition.animateFloat( + initialValue = 1f, + targetValue = if (isFocusing) 0.8f else 1f, + animationSpec = infiniteRepeatable( + animation = tween(300), + repeatMode = RepeatMode.Reverse + ), + label = "focusScale" + ) + + // 透明度动画 + val alpha by animateFloatAsState( + targetValue = when { + isFocusing -> 1f + focusSuccess == true -> 0.8f + focusSuccess == false -> 0.5f + else -> 0f + }, + animationSpec = tween(300), + label = "focusAlpha" + ) + + // 颜色 + val color = when { + isFocusing -> Color.White + focusSuccess == true -> Color.Green + else -> Color.Red + } + + // 自动隐藏 + LaunchedEffect(focusSuccess) { + if (focusSuccess != null) { + kotlinx.coroutines.delay(1500) + // 这里应该通知父组件清除对焦点,但为简化暂时不处理 + } + } + + Canvas( + modifier = modifier.fillMaxSize() + ) { + val x = position.first * size.width + val y = position.second * size.height + val boxSize = 60.dp.toPx() * scale + val halfSize = boxSize / 2 + val cornerLength = 15.dp.toPx() + val strokeWidth = 2.dp.toPx() + + val drawColor = color.copy(alpha = alpha) + + // 左上角 + drawLine( + color = drawColor, + start = Offset(x - halfSize, y - halfSize), + end = Offset(x - halfSize + cornerLength, y - halfSize), + strokeWidth = strokeWidth + ) + drawLine( + color = drawColor, + start = Offset(x - halfSize, y - halfSize), + end = Offset(x - halfSize, y - halfSize + cornerLength), + strokeWidth = strokeWidth + ) + + // 右上角 + drawLine( + color = drawColor, + start = Offset(x + halfSize, y - halfSize), + end = Offset(x + halfSize - cornerLength, y - halfSize), + strokeWidth = strokeWidth + ) + drawLine( + color = drawColor, + start = Offset(x + halfSize, y - halfSize), + end = Offset(x + halfSize, y - halfSize + cornerLength), + strokeWidth = strokeWidth + ) + + // 左下角 + drawLine( + color = drawColor, + start = Offset(x - halfSize, y + halfSize), + end = Offset(x - halfSize + cornerLength, y + halfSize), + strokeWidth = strokeWidth + ) + drawLine( + color = drawColor, + start = Offset(x - halfSize, y + halfSize), + end = Offset(x - halfSize, y + halfSize - cornerLength), + strokeWidth = strokeWidth + ) + + // 右下角 + drawLine( + color = drawColor, + start = Offset(x + halfSize, y + halfSize), + end = Offset(x + halfSize - cornerLength, y + halfSize), + strokeWidth = strokeWidth + ) + drawLine( + color = drawColor, + start = Offset(x + halfSize, y + halfSize), + end = Offset(x + halfSize, y + halfSize - cornerLength), + strokeWidth = strokeWidth + ) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/theme/Color.kt b/app/src/main/java/com/hinnka/mycamera/ui/theme/Color.kt new file mode 100644 index 00000000..ddc55eb8 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/theme/Color.kt @@ -0,0 +1,32 @@ +package com.hinnka.mycamera.ui.theme + +import androidx.compose.ui.graphics.Color + +// 主题色 +val AccentOrange = Color(0xFFFF6B35) +val AccentOrangeLight = Color(0xFFFF8A5C) +val AccentOrangeDark = Color(0xFFE55A2B) + +// 深色主题 +val DarkBackground = Color(0xFF0D0D0D) +val DarkSurface = Color(0xFF1A1A1A) +val DarkSurfaceVariant = Color(0xFF2D2D2D) + +// 文字颜色 +val TextPrimary = Color(0xFFFFFFFF) +val TextSecondary = Color(0xB3FFFFFF) // 70% white +val TextTertiary = Color(0x80FFFFFF) // 50% white + +// 状态颜色 +val SuccessGreen = Color(0xFF4CAF50) +val ErrorRed = Color(0xFFE53935) +val WarningYellow = Color(0xFFFFC107) + +// 旧颜色(保持兼容) +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/app/src/main/java/com/hinnka/mycamera/ui/theme/Theme.kt b/app/src/main/java/com/hinnka/mycamera/ui/theme/Theme.kt new file mode 100644 index 00000000..630d8959 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/theme/Theme.kt @@ -0,0 +1,80 @@ +package com.hinnka.mycamera.ui.theme + +import android.app.Activity +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +private val DarkColorScheme = darkColorScheme( + primary = AccentOrange, + secondary = AccentOrangeLight, + tertiary = AccentOrangeDark, + background = DarkBackground, + surface = DarkSurface, + surfaceVariant = DarkSurfaceVariant, + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = TextPrimary, + onSurface = TextPrimary, + onSurfaceVariant = TextSecondary +) + +private val LightColorScheme = lightColorScheme( + primary = AccentOrange, + secondary = AccentOrangeLight, + tertiary = AccentOrangeDark +) + +@Composable +fun PhotonCameraTheme( + darkTheme: Boolean = true, // 相机应用默认深色主题 + dynamicColor: Boolean = false, // 禁用动态颜色以保持一致性 + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = Color.Transparent.toArgb() + window.navigationBarColor = Color.Transparent.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} + +// 保持旧主题函数用于兼容 +@Composable +fun MyCameraTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + PhotonCameraTheme(darkTheme = darkTheme, dynamicColor = dynamicColor, content = content) +} \ No newline at end of file diff --git a/app/src/main/java/com/hinnka/mycamera/ui/theme/Type.kt b/app/src/main/java/com/hinnka/mycamera/ui/theme/Type.kt new file mode 100644 index 00000000..358536a2 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package com.hinnka.mycamera.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt new file mode 100644 index 00000000..a79bff10 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -0,0 +1,237 @@ +package com.hinnka.mycamera.viewmodel + +import android.app.Application +import android.content.ContentValues +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.util.Log +import android.util.Size +import android.view.Surface +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.hinnka.mycamera.camera.AspectRatio +import com.hinnka.mycamera.camera.CameraController +import com.hinnka.mycamera.camera.CameraState +import com.hinnka.mycamera.camera.CameraUtils +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import java.io.File +import java.io.FileOutputStream +import java.text.SimpleDateFormat +import java.util.* + +/** + * 相机 ViewModel + */ +class CameraViewModel(application: Application) : AndroidViewModel(application) { + + companion object { + private const val TAG = "CameraViewModel" + } + + private val cameraController = CameraController(application) + + val state: StateFlow = cameraController.state + + // 存储是否为横屏模式,而不是角度值,减少重组次数 + var isLandscape by mutableStateOf(false) + private set + + // 存储旋转角度,用于UI旋转 + // 0: 竖屏正常, 90: 右侧朝上(顺时针90°), 270: 左侧朝上(逆时针90°) + var rotationDegrees by mutableStateOf(0f) + private set + + // 更新方向,只在横竖屏切换时才更新状态 + fun updateOrientation(orientation: Int) { + when { + // 右侧朝上(手机顺时针旋转90°) + orientation in 45..135 -> { + if (!isLandscape || rotationDegrees != 90f) { + isLandscape = true + rotationDegrees = 90f + cameraController.setDeviceRotation(90) + } + } + // 左侧朝上(手机逆时针旋转90°) + orientation in 225..315 -> { + if (!isLandscape || rotationDegrees != 270f) { + isLandscape = true + rotationDegrees = 270f + cameraController.setDeviceRotation(270) + } + } + // 竖屏 + else -> { + if (isLandscape) { + isLandscape = false + rotationDegrees = 0f + cameraController.setDeviceRotation(0) + } + } + } + } + + init { + cameraController.initialize() + cameraController.onImageCaptured = { bytes -> + viewModelScope.launch { + saveImage(bytes) + } + } + } + + /** + * 打开相机 + */ + fun openCamera(surface: Surface) { + cameraController.openCamera(surface) + } + + /** + * 关闭相机 + */ + fun closeCamera() { + cameraController.closeCamera() + } + + /** + * 检查相机状态并在必要时恢复 + * 用于从后台切换回 App 时调用 + */ + fun checkAndRecoverCamera() { + cameraController.checkAndRecoverCamera() + } + + /** + * 拍照 + */ + fun capture() { + cameraController.capture() + } + + /** + * 切换摄像头 + */ + fun switchCamera() { + cameraController.switchCamera() + } + + /** + * 设置曝光补偿 + */ + fun setExposureCompensation(value: Int) { + cameraController.setExposureCompensation(value) + } + + /** + * 设置自动曝光 + */ + fun setAutoExposure(enabled: Boolean) { + cameraController.setAutoExposure(enabled) + } + + /** + * 设置 ISO + */ + fun setIso(value: Int) { + cameraController.setIso(value) + } + + /** + * 设置快门速度 + */ + fun setShutterSpeed(value: Long) { + cameraController.setShutterSpeed(value) + } + + /** + * 设置变焦倍数 + */ + fun setZoomRatio(ratio: Float) { + cameraController.setZoomRatio(ratio) + } + + /** + * 设置画面比例 + */ + fun setAspectRatio(ratio: AspectRatio) { + cameraController.setAspectRatio(ratio) + } + + /** + * 点击对焦 + */ + fun focusOnPoint(x: Float, y: Float, viewWidth: Int, viewHeight: Int) { + cameraController.focusOnPoint(x, y, viewWidth, viewHeight) + } + + /** + * 获取预览尺寸(固定 16:9) + * 使用固定尺寸,不同画面比例通过 UI 裁切实现 + */ + fun getPreviewSize(): Size { + val currentState = state.value + return CameraUtils.getFixedPreviewSize( + getApplication(), + currentState.currentCameraId + ) + } + + /** + * 保存图片 + */ + private fun saveImage(bytes: ByteArray) { + val context = getApplication() + val filename = "IMG_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.jpg" + + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // Android 10+ 使用 MediaStore + val contentValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, filename) + put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") + put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") + } + + val uri = context.contentResolver.insert( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + contentValues + ) + + uri?.let { + context.contentResolver.openOutputStream(it)?.use { outputStream -> + outputStream.write(bytes) + } + Log.d(TAG, "Image saved: $uri") + } + } else { + // 低版本直接写文件 + val directory = File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), + "PhotonCamera" + ) + if (!directory.exists()) { + directory.mkdirs() + } + + val file = File(directory, filename) + FileOutputStream(file).use { outputStream -> + outputStream.write(bytes) + } + Log.d(TAG, "Image saved: ${file.absolutePath}") + } + } catch (e: Exception) { + Log.e(TAG, "Failed to save image", e) + } + } + + override fun onCleared() { + super.onCleared() + cameraController.release() + } +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000..6b753e21 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 00000000..6107c771 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 00000000..6f3b755b --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 00000000..6f3b755b --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 00000000..c209e78e Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 00000000..b2dfe3d1 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 00000000..4f0f1d64 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 00000000..62b611da Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 00000000..948a3070 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..1b9a6956 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 00000000..28d4b77f Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..9287f508 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 00000000..aa7d6427 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 00000000..9126ae37 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml new file mode 100644 index 00000000..4e533b96 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -0,0 +1,33 @@ + + + 光子相机 + + + 拍摄 + 切换相机 + 设置 + + + 曝光补偿 + 感光度 + 快门速度 + 自动 + + + 对焦 + 点击对焦 + + + 画面比例 + 3:2 + 4:3 + 16:9 + 1:1 + + + 需要相机权限 + 授予权限 + + + 变焦 + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..f8c6127d --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..617744e6 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,32 @@ + + Photon Camera + + + Capture + Switch Camera + Settings + + + EV + ISO + Shutter + AUTO + + + Focus + Tap to focus + + + Aspect Ratio + 3:2 + 4:3 + 16:9 + 1:1 + + + Camera permission is required + Grant Permission + + + Zoom + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 00000000..1954b803 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +