feat: custom watermark

This commit is contained in:
zhoubinjia committed 2026-01-15 16:18:39 +08:00
1 parent 7bf3ce0c6c
commit fb2d6fe4cf
5 files changed
+497 -186

No files matched your search

+1 -1
View File
@@ -9,9 +9,9 @@
- [x] 批量导入
- [x] LUT自定义命名
- [x] 静音拍照添加震动
- [x] 定制水印
- [ ] 影调配方
- [ ] raw 格式照片处理 / Halide
- [ ] 定制水印
- [ ] 视频拍摄
# 竞品参考
@@ -19,19 +19,19 @@ import com.hinnka.mycamera.utils.PLog
* 使用 Android Canvas 渲染带边框水印的照片
*/
class FrameRenderer(private val context: Context) {
companion object {
private const val TAG = "FrameRenderer"
}
// 缓存的 Paint 对象
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.LEFT
}
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG)
/**
* 渲染带边框的照片
*
@@ -51,80 +51,88 @@ class FrameRenderer(private val context: Context) {
PLog.d(TAG, "render: $metadata")
val layout = template.layout
val expectedHeight = originalBitmap.height * 0.08f
val scale = expectedHeight / dpToPx(80) // 以 80dp 为基准高度计算缩放比例
val frameHeight = (dpToPx(layout.heightDp) * scale).toInt()
val padding = (dpToPx(layout.paddingDp) * scale).toInt()
val borderWidth = (dpToPx(layout.borderWidthDp) * scale).toInt()
// 计算输出尺寸
val outputWidth: Int
val outputHeight: Int
when (layout.position) {
FramePosition.BOTTOM -> {
outputWidth = originalBitmap.width
outputHeight = originalBitmap.height + frameHeight
}
FramePosition.TOP -> {
outputWidth = originalBitmap.width
outputHeight = originalBitmap.height + frameHeight
}
FramePosition.BOTH -> {
outputWidth = originalBitmap.width
outputHeight = originalBitmap.height + frameHeight * 2
}
FramePosition.OVERLAY -> {
outputWidth = originalBitmap.width
outputHeight = originalBitmap.height
}
FramePosition.BORDER -> {
// 四周边框 + 底部信息区
outputWidth = originalBitmap.width + borderWidth * 2
outputHeight = originalBitmap.height + borderWidth * 2 + frameHeight
}
}
// 创建输出 Bitmap
val output = createBitmap(outputWidth, outputHeight)
val canvas = Canvas(output)
// OVERLAY 模式不需要绘制整体背景
if (layout.position != FramePosition.OVERLAY) {
backgroundPaint.color = layout.backgroundColor
canvas.drawRect(0f, 0f, outputWidth.toFloat(), outputHeight.toFloat(), backgroundPaint)
}
// 绘制原图
val photoLeft: Float
val photoTop: Float
when (layout.position) {
FramePosition.BOTTOM -> {
photoLeft = 0f
photoTop = 0f
}
FramePosition.TOP -> {
photoLeft = 0f
photoTop = frameHeight.toFloat()
}
FramePosition.BOTH -> {
photoLeft = 0f
photoTop = frameHeight.toFloat()
}
FramePosition.OVERLAY -> {
photoLeft = 0f
photoTop = 0f
}
FramePosition.BORDER -> {
photoLeft = borderWidth.toFloat()
photoTop = borderWidth.toFloat()
}
}
canvas.drawBitmap(originalBitmap, photoLeft, photoTop, null)
// 绘制边框内容
when (layout.position) {
FramePosition.BOTTOM -> {
@@ -137,6 +145,7 @@ class FrameRenderer(private val context: Context) {
scale = scale
)
}
FramePosition.TOP -> {
drawFrameContent(
canvas, template.elements, metadata, showAppBranding,
@@ -147,6 +156,7 @@ class FrameRenderer(private val context: Context) {
scale = scale
)
}
FramePosition.BOTH -> {
// 顶部
drawFrameContent(
@@ -167,10 +177,11 @@ class FrameRenderer(private val context: Context) {
scale = scale
)
}
FramePosition.OVERLAY -> {
// 叠加模式:绘制从全透明到半透明的渐变背景
val overlayTop = (originalBitmap.height - frameHeight).toFloat()
// 创建线性渐变:从顶部全透明到底部半透明
val gradientShader = LinearGradient(
0f, overlayTop,
@@ -182,7 +193,7 @@ class FrameRenderer(private val context: Context) {
backgroundPaint.shader = gradientShader
canvas.drawRect(0f, overlayTop, outputWidth.toFloat(), outputHeight.toFloat(), backgroundPaint)
backgroundPaint.shader = null // 重置 shader
// 绘制水印内容
drawFrameContent(
canvas, template.elements, metadata, showAppBranding,
@@ -193,6 +204,7 @@ class FrameRenderer(private val context: Context) {
scale = scale
)
}
FramePosition.BORDER -> {
// 四周边框模式:底部信息区
val infoTop = (originalBitmap.height + borderWidth * 2).toFloat()
@@ -206,10 +218,10 @@ class FrameRenderer(private val context: Context) {
)
}
}
return output
}
private fun drawFrameContent(
canvas: Canvas,
elements: List<FrameElement>,
@@ -221,18 +233,29 @@ class FrameRenderer(private val context: Context) {
bottom: Float,
scale: Float = 1f
) {
// 将元素按对齐方式分组
val startElements = elements.filter { getAlignment(it) == ElementAlignment.START }
val centerElements = elements.filter { getAlignment(it) == ElementAlignment.CENTER }
val endElements = elements.filter { getAlignment(it) == ElementAlignment.END }
// 将元素按对齐方式分组并过滤不可见元素
val startElements = filterVisibleGroup(
elements.filter { getAlignment(it) == ElementAlignment.START },
metadata,
showAppBranding
)
val centerElements = filterVisibleGroup(
elements.filter { getAlignment(it) == ElementAlignment.CENTER },
metadata,
showAppBranding
)
val endElements =
filterVisibleGroup(elements.filter { getAlignment(it) == ElementAlignment.END }, metadata, showAppBranding)
val visibleElements = startElements + centerElements + endElements
// 获取所有行号以计算行数
val allLines = elements.map { getLine(it) }.filter { it >= 0 }.distinct().sorted()
val allLines = visibleElements.map { getLine(it) }.filter { it >= 0 }.distinct().sorted()
val lineCount = allLines.size
val height = bottom - top
val logoLineSet = elements.filterIsInstance<FrameElement.Logo>().map { it.line }.toSet()
val logoLineSet = visibleElements.filterIsInstance<FrameElement.Logo>().map { it.line }.toSet()
val lineWeights = allLines.map { if (logoLineSet.contains(it)) 3f else 1.0f }
val totalWeight = lineWeights.sum()
@@ -241,7 +264,7 @@ class FrameRenderer(private val context: Context) {
*/
fun getLineCenterY(line: Int): Float {
if (line == -1 || lineCount <= 1) return top + height / 2f
val lineIndex = allLines.indexOf(line)
if (lineIndex == -1) return top + height / 2f
@@ -251,13 +274,13 @@ class FrameRenderer(private val context: Context) {
else -> 0.84f
}
val startOffset = (1f - contentRatio) / 2f
var currentYOffset = 0f
for (i in 0 until lineIndex) {
currentYOffset += (lineWeights[i] / totalWeight) * contentRatio
}
val currentLineWeightRatio = (lineWeights[lineIndex] / totalWeight) * contentRatio
return top + (startOffset + currentYOffset + currentLineWeightRatio / 2f) * height
}
@@ -266,16 +289,16 @@ class FrameRenderer(private val context: Context) {
*/
fun drawAlignedGroup(groupElements: List<FrameElement>, initialX: Float, leftToRight: Boolean) {
val currentXPerLine = mutableMapOf<Int, Float>()
for (element in if (leftToRight) groupElements else groupElements.reversed()) {
val line = getLine(element)
val centerY = getLineCenterY(line)
val x = currentXPerLine.getOrDefault(line, initialX)
val width = drawElement(canvas, element, metadata, showAppBranding, x, centerY, leftToRight, scale)
val nextX = if (leftToRight) x + width else x - width
if (line == -1) {
// 全局元素,推进所有行的 X 坐标
currentXPerLine[-1] = nextX
@@ -296,17 +319,17 @@ class FrameRenderer(private val context: Context) {
val elementsByLine = groupElements.groupBy { getLine(it) }
val availableWidth = right - left
val elementSpacing = dpToPx(8) * scale // 元素间距
for ((line, lineElements) in elementsByLine) {
// 计算该行的总宽度(扣除最后一个元素的间距)
val lineWidth = lineElements.sumOf {
measureElementWidth(it, metadata, showAppBranding, scale).toDouble()
val lineWidth = lineElements.sumOf {
measureElementWidth(it, metadata, showAppBranding, scale).toDouble()
}.toFloat() - elementSpacing // 减去最后一个元素多余的间距
// 计算该行的起始 X 位置(居中)
val startX = left + (availableWidth - lineWidth) / 2f
val centerY = getLineCenterY(line)
// 绘制该行的所有元素
var currentX = startX
for ((index, element) in lineElements.withIndex()) {
@@ -320,14 +343,14 @@ class FrameRenderer(private val context: Context) {
// 绘制左侧元素
drawAlignedGroup(startElements, left, true)
// 绘制右侧元素
drawAlignedGroup(endElements, right, false)
// 绘制中间元素(每行独立居中)
drawCenteredGroup(centerElements)
}
/**
* 获取元素对齐方式
*/
@@ -351,10 +374,7 @@ class FrameRenderer(private val context: Context) {
is FrameElement.Spacer -> element.line
}
}
/**
* 测量元素组的总宽度
*/
private fun measureElementsWidth(
elements: List<FrameElement>,
metadata: PhotoMetadata,
@@ -363,9 +383,9 @@ class FrameRenderer(private val context: Context) {
): Float {
val xPerLine = mutableMapOf<Int, Float>()
for (element in elements) {
val line = getLine(element)
val width = measureElementWidth(element, metadata, showAppBranding, scale)
val line = getLine(element)
if (line == -1) {
val max = (xPerLine.values.maxOrNull() ?: 0f) + width
xPerLine[-1] = max
@@ -379,7 +399,50 @@ class FrameRenderer(private val context: Context) {
}
return xPerLine.values.maxOrNull() ?: 0f
}
private fun isElementVisible(element: FrameElement, metadata: PhotoMetadata, showAppBranding: Boolean): Boolean {
return when (element) {
is FrameElement.Text -> getTextContent(element, metadata, showAppBranding) != null
is FrameElement.Logo -> {
if (element.logoType == LogoType.APP && !showAppBranding) return false
val logoKey = metadata.customProperties["LOGO"]
logoKey != "none"
}
is FrameElement.Divider -> true
is FrameElement.Spacer -> true
}
}
private fun filterVisibleGroup(
elements: List<FrameElement>,
metadata: PhotoMetadata,
showAppBranding: Boolean
): List<FrameElement> {
val initiallyVisible = elements.filter { isElementVisible(it, metadata, showAppBranding) }
val result = mutableListOf<FrameElement>()
for (i in initiallyVisible.indices) {
val element = initiallyVisible[i]
if (element is FrameElement.Divider) {
val line = getLine(element)
// A vertical divider needs a non-divider visible element before AND after it in the same line
if (element.orientation == DividerOrientation.VERTICAL) {
val hasBefore = initiallyVisible.take(i).any { getLine(it) == line && it !is FrameElement.Divider }
val hasAfter =
initiallyVisible.drop(i + 1).any { getLine(it) == line && it !is FrameElement.Divider }
if (hasBefore && hasAfter) {
result.add(element)
}
} else {
result.add(element)
}
} else {
result.add(element)
}
}
return result
}
/**
* 测量单个元素宽度
*/
@@ -396,10 +459,14 @@ class FrameRenderer(private val context: Context) {
textPaint.typeface = getTypeface(element.fontWeight)
textPaint.measureText(text) + dpToPx(8) * scale
}
is FrameElement.Logo -> {
val logoKey = metadata.customProperties["LOGO"]
if (logoKey == "none") return 0f
val (bmpW, _) = measureLogoSize(element, metadata, scale)
bmpW + dpToPx(element.marginDp) * scale * 2 + dpToPx(8) * scale
}
is FrameElement.Divider -> {
if (element.orientation == DividerOrientation.VERTICAL) {
(dpToPx(element.thicknessDp) + dpToPx(element.marginDp * 2)) * scale
@@ -407,12 +474,13 @@ class FrameRenderer(private val context: Context) {
0f
}
}
is FrameElement.Spacer -> {
dpToPx(element.widthDp) * scale
}
}
}
/**
* 绘制单个元素
*
@@ -429,13 +497,33 @@ class FrameRenderer(private val context: Context) {
scale: Float = 1f
): Float {
return when (element) {
is FrameElement.Text -> drawTextElement(canvas, element, metadata, showAppBranding, x, centerY, leftToRight, scale)
is FrameElement.Logo -> drawLogoElement(canvas, element, showAppBranding, x, centerY, leftToRight, metadata, scale)
is FrameElement.Text -> drawTextElement(
canvas,
element,
metadata,
showAppBranding,
x,
centerY,
leftToRight,
scale
)
is FrameElement.Logo -> drawLogoElement(
canvas,
element,
showAppBranding,
x,
centerY,
leftToRight,
metadata,
scale
)
is FrameElement.Divider -> drawDividerElement(canvas, element, x, centerY, leftToRight, scale)
is FrameElement.Spacer -> dpToPx(element.widthDp) * scale
}
}
/**
* 绘制文本元素
*/
@@ -450,22 +538,22 @@ class FrameRenderer(private val context: Context) {
scale: Float = 1f
): Float {
val text = getTextContent(element, metadata, showAppBranding) ?: return x
textPaint.color = element.color
textPaint.textSize = spToPx(element.fontSizeSp) * scale
textPaint.typeface = getTypeface(element.fontWeight)
val textWidth = textPaint.measureText(text)
val textHeight = textPaint.descent() - textPaint.ascent()
val textY = centerY - (textPaint.descent() + textPaint.ascent()) / 2
val drawX = if (leftToRight) x else x - textWidth
canvas.drawText(text, drawX, textY, textPaint)
val spacing = dpToPx(8) * scale
return textWidth + spacing
}
/**
* 获取文本内容
*/
@@ -477,15 +565,18 @@ class FrameRenderer(private val context: Context) {
val content = when (element.textType) {
TextType.DEVICE_MODEL -> metadata.deviceModel
TextType.BRAND -> metadata.brand
TextType.DATE -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "yyyy.MM.dd")
TextType.DATE -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "yyyy.MM.dd")
}
TextType.TIME -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "HH:mm")
TextType.TIME -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "HH:mm")
}
TextType.DATETIME -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "yyyy.MM.dd HH:mm")
TextType.DATETIME -> metadata.dateTaken?.let {
formatDate(it, element.format ?: "yyyy.MM.dd HH:mm")
}
TextType.LOCATION -> metadata.location
TextType.ISO -> metadata.iso?.let { "ISO $it" }
TextType.SHUTTER_SPEED -> metadata.shutterSpeed
@@ -496,19 +587,27 @@ class FrameRenderer(private val context: Context) {
TextType.CUSTOM -> element.format
TextType.APP_NAME -> if (showAppBranding) context.getString(R.string.app_name) else null
} ?: return null
// 允许用户自定义覆盖内容
val finalContent = metadata.customProperties[element.textType.name] ?: content
val prefix = element.prefix ?: ""
val suffix = element.suffix ?: ""
return "$prefix$content$suffix"
return "$prefix$finalContent$suffix"
}
private fun measureLogoSize(element: FrameElement.Logo, metadata: PhotoMetadata?, scale: Float = 1f): Pair<Int, Int> {
private fun measureLogoSize(
element: FrameElement.Logo,
metadata: PhotoMetadata?,
scale: Float = 1f
): Pair<Int, Int> {
val size = (dpToPx(element.sizeDp) * scale).toInt()
// 获取对应的 drawable
val logoKey = metadata?.customProperties?.get("LOGO")
val drawableRes = when (element.logoType) {
LogoType.APP -> R.mipmap.ic_launcher_round
LogoType.BRAND -> getBrandLogoDrawable(metadata?.brand, element.light)
LogoType.BRAND -> getBrandLogoDrawable(logoKey ?: metadata?.brand, element.light)
}
try {
@@ -533,7 +632,7 @@ class FrameRenderer(private val context: Context) {
return 0 to 0
}
}
/**
* 绘制 Logo 元素
*/
@@ -552,32 +651,35 @@ class FrameRenderer(private val context: Context) {
return x
}
val margin = dpToPx(element.marginDp) * scale
val size = (dpToPx(element.sizeDp) * scale).toInt()
// 获取对应的 drawable
val logoKey = metadata?.customProperties?.get("LOGO")
if (logoKey == "none") return 0f
val drawableRes = when (element.logoType) {
LogoType.APP -> R.mipmap.ic_launcher_round
LogoType.BRAND -> getBrandLogoDrawable(metadata?.brand, element.light)
LogoType.BRAND -> getBrandLogoDrawable(logoKey ?: metadata?.brand, element.light)
}
try {
val drawable = context.getDrawable(drawableRes) ?: return x
val (bmpW, bmpH) = measureLogoSize(element, metadata, scale)
val bitmap = drawable.toBitmap(bmpW.coerceAtLeast(1), bmpH.coerceAtLeast(1))
val drawX = if (leftToRight) (x + margin) else (x - size - margin)
val drawX = if (leftToRight) (x + margin) else (x - bmpW - margin)
val drawY = centerY - bitmap.height / 2f
canvas.drawBitmap(bitmap, drawX, drawY, null)
return bmpW + margin * 2
return bmpW + margin * 2 + dpToPx(8) * scale
} catch (e: Exception) {
PLog.e(TAG, "Failed to draw logo", e)
return 0f
}
}
/**
* 根据品牌名获取对应的 Logo drawable
*
@@ -612,8 +714,8 @@ class FrameRenderer(private val context: Context) {
)
private fun getBrandLogoDrawable(brand: String?, light: Boolean = false): Int {
if (brand == null) return R.mipmap.ic_launcher_round
if (brand == null || brand == "none") return R.mipmap.ic_launcher_round
// 尝试获取品牌特定的 Logo
val brandLower = brand.lowercase()
val drawableRes = logoMap.firstNotNullOfOrNull { (key, value) ->
@@ -623,7 +725,7 @@ class FrameRenderer(private val context: Context) {
// 使用通用品牌图标作为后备
return drawableRes ?: R.mipmap.ic_launcher_round
}
/**
* 绘制分隔线元素
*/
@@ -637,12 +739,12 @@ class FrameRenderer(private val context: Context) {
): Float {
linePaint.color = element.color
linePaint.strokeWidth = dpToPx(element.thicknessDp) * scale
val length = dpToPx(element.lengthDp) * scale
val margin = dpToPx(element.marginDp) * scale
val drawX = if (leftToRight) x + margin else x - margin
if (element.orientation == DividerOrientation.VERTICAL) {
canvas.drawLine(
drawX, centerY - length / 2f,
@@ -660,7 +762,7 @@ class FrameRenderer(private val context: Context) {
return length + margin * 2
}
}
/**
* 生成预览缩略图
*/
@@ -674,14 +776,14 @@ class FrameRenderer(private val context: Context) {
val scaledWidth = targetWidth
val scaledHeight = (originalBitmap.height * scale).toInt()
val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, scaledWidth, scaledHeight, true)
// 渲染边框
val metadata = PhotoMetadata.createDefault(scaledWidth, scaledHeight)
return render(scaledBitmap, template, metadata, showAppBranding = true)
}
// 工具方法
private fun dpToPx(dp: Int): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
@@ -689,7 +791,7 @@ class FrameRenderer(private val context: Context) {
context.resources.displayMetrics
).toInt()
}
private fun spToPx(sp: Int): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
@@ -697,7 +799,7 @@ class FrameRenderer(private val context: Context) {
context.resources.displayMetrics
).toInt()
}
private fun formatDate(timestamp: Long, format: String): String {
return try {
SimpleDateFormat(format, Locale.getDefault()).format(Date(timestamp))
@@ -705,7 +807,7 @@ class FrameRenderer(private val context: Context) {
""
}
}
private fun getTypeface(weight: FontWeight): Typeface {
return when (weight) {
FontWeight.NORMAL -> Typeface.DEFAULT
@@ -40,6 +40,8 @@ data class PhotoMetadata(
val focalLength35mm: String? = null,
val aperture: String? = null,
val isImported: Boolean = false,
// 边框水印自定义
val customProperties: Map<String, String> = emptyMap(),
// 导出到系统相册的 URI 列表
val exportedUris: List<String> = emptyList()
) {
@@ -71,14 +73,18 @@ data class PhotoMetadata(
put("focalLength35mm", focalLength35mm ?: JSONObject.NULL)
put("aperture", aperture ?: JSONObject.NULL)
put("isImported", isImported)
// 边框水印自定义
val customPropsObj = JSONObject()
customProperties.forEach { (k, v) -> customPropsObj.put(k, v) }
put("customProperties", customPropsObj)
// 导出的 URI 列表
put("exportedUris", org.json.JSONArray(exportedUris))
}.toString(2)
}
companion object {
private const val TAG = "PhotoMetadata"
fun fromJson(json: String): PhotoMetadata? {
return try {
val obj = JSONObject(json)
@@ -113,6 +119,12 @@ data class PhotoMetadata(
focalLength35mm = if (obj.isNull("focalLength35mm")) null else obj.optString("focalLength35mm"),
aperture = if (obj.isNull("aperture")) null else obj.optString("aperture"),
isImported = obj.optBoolean("isImported", false),
customProperties = mutableMapOf<String, String>().apply {
val customPropsObj = obj.optJSONObject("customProperties")
customPropsObj?.keys()?.forEach { key ->
put(key, customPropsObj.getString(key))
}
},
exportedUris = exportedUris
)
} catch (e: Exception) {
@@ -120,7 +132,7 @@ data class PhotoMetadata(
null
}
}
/**
* 从系统信息创建默认元数据
*/
@@ -141,14 +153,16 @@ data class PhotoMetadata(
return try {
context.contentResolver.openInputStream(uri)?.use { inputStream ->
val exif = ExifInterface(inputStream)
val model = exif.getAttribute(ExifInterface.TAG_MODEL)
val make = exif.getAttribute(ExifInterface.TAG_MAKE)
val dateStr = exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL) ?: exif.getAttribute(ExifInterface.TAG_DATETIME)
val dateStr = exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL) ?: exif.getAttribute(
ExifInterface.TAG_DATETIME
)
val iso = exif.getAttributeInt(ExifInterface.TAG_ISO_SPEED_RATINGS, 0).takeIf { it > 0 }
?: exif.getAttributeInt(ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY, 0).takeIf { it > 0 }
val shutterSpeed = exif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)?.let {
try {
val time = it.toDouble()
@@ -161,8 +175,9 @@ data class PhotoMetadata(
it
}
}
val aperture = exif.getAttributeDouble(ExifInterface.TAG_F_NUMBER, 0.0).takeIf { it > 0 }?.let { "f/${String.format("%.1f", it)}" }
val aperture = exif.getAttributeDouble(ExifInterface.TAG_F_NUMBER, 0.0).takeIf { it > 0 }
?.let { "f/${String.format("%.1f", it)}" }
val focalLength = exif.getAttributeDouble(ExifInterface.TAG_FOCAL_LENGTH, 0.0).let {
"${it.toInt()}mm"
}
@@ -5,6 +5,7 @@ import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -36,12 +37,16 @@ import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.hinnka.mycamera.R
import com.hinnka.mycamera.frame.TextType
import com.hinnka.mycamera.ui.components.CustomSlider
import com.hinnka.mycamera.ui.components.PaymentDialog
import com.hinnka.mycamera.ui.theme.AccentOrange
import com.hinnka.mycamera.viewmodel.GalleryViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* 照片编辑界面
@@ -62,30 +67,40 @@ fun PhotoEditScreen(
val editLutConfig = viewModel.editLutConfig
val availableLuts = viewModel.availableLuts
val showPaymentDialog = viewModel.showPaymentDialog
var isSaving by remember { mutableStateOf(false) }
var showExportDialog by remember { mutableStateOf(false) }
var isLoadingPreview by remember { mutableStateOf(false) }
val lutScrollState = rememberLazyListState()
val frameScrollState = rememberLazyListState()
BackHandler {
viewModel.exitEditMode()
onBack()
}
// 预览 Bitmap 状态
var previewBitmap by remember { mutableStateOf<Bitmap?>(null) }
var lutPreviews by remember { mutableStateOf<List<Bitmap?>>(emptyList()) }
// 边框编辑状态
val editFrameId = viewModel.editFrameId
val availableFrames = viewModel.availableFrames
// 当编辑参数变化时更新预览
LaunchedEffect(currentPhoto, editLutId, editLutConfig, editLutIntensity, rotation, brightness, editFrameId) {
val customPropertiesList = viewModel.editCustomProperties.entries.toList()
LaunchedEffect(
currentPhoto,
editLutId,
editLutConfig,
editLutIntensity,
rotation,
brightness,
editFrameId,
customPropertiesList
) {
if (currentPhoto == null) return@LaunchedEffect
isLoadingPreview = true
previewBitmap = withContext(Dispatchers.IO) {
viewModel.getPreviewBitmap(currentPhoto)
@@ -113,14 +128,14 @@ fun PhotoEditScreen(
}
}
}
if (currentPhoto == null) {
LaunchedEffect(Unit) {
onBack()
}
return
}
Scaffold(
topBar = {
TopAppBar(
@@ -171,7 +186,7 @@ fun PhotoEditScreen(
)
}
}
// 导出(烘焙)按钮
/*IconButton(
onClick = { showExportDialog = true },
@@ -225,7 +240,7 @@ fun PhotoEditScreen(
modifier = Modifier.fillMaxSize()
)
}
// 加载指示器
if (isLoadingPreview) {
CircularProgressIndicator(
@@ -233,7 +248,7 @@ fun PhotoEditScreen(
modifier = Modifier.size(48.dp)
)
}
// LUT 指示器
if (editLutId != null) {
Box(
@@ -253,7 +268,7 @@ fun PhotoEditScreen(
}
}
}
// 编辑控制区域
Surface(
color = Color(0xFF1A1A1A),
@@ -269,9 +284,9 @@ fun PhotoEditScreen(
color = Color.White,
fontSize = 16.sp
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(12.dp),
state = lutScrollState
@@ -288,10 +303,10 @@ fun PhotoEditScreen(
)
}
}
// LUT 强度滑块(LUT 始终可用)
Spacer(modifier = Modifier.height(12.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
@@ -309,7 +324,7 @@ fun PhotoEditScreen(
valueRange = 0f..1f,
modifier = Modifier.weight(1f)
)
Text(
text = "${(editLutIntensity * 100).toInt()}%",
color = Color.White.copy(alpha = 0.7f),
@@ -317,19 +332,19 @@ fun PhotoEditScreen(
modifier = Modifier.width(40.dp)
)
}
Spacer(modifier = Modifier.height(16.dp))
// 边框水印选择器
Text(
text = stringResource(R.string.frame),
color = Color.White,
fontSize = 16.sp
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(12.dp),
state = frameScrollState
@@ -354,11 +369,33 @@ fun PhotoEditScreen(
)
}
}
if (editFrameId != null) {
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = { viewModel.showWatermarkSheet = true },
colors = ButtonDefaults.buttonColors(
containerColor = Color.White.copy(alpha = 0.1f)
),
shape = RoundedCornerShape(8.dp),
modifier = Modifier.fillMaxWidth()
) {
Text(text = "调整水印", color = Color.White)
}
}
}
}
}
}
if (viewModel.showWatermarkSheet) {
WatermarkEditSheet(
viewModel = viewModel,
onDismiss = { viewModel.showWatermarkSheet = false }
)
}
// 导出确认对话框
if (showExportDialog) {
AlertDialog(
@@ -505,9 +542,9 @@ private fun LutOption(
}
}
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = name,
color = if (isSelected) AccentOrange else Color.White.copy(alpha = 0.7f),
@@ -518,3 +555,137 @@ private fun LutOption(
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun WatermarkEditSheet(
viewModel: GalleryViewModel,
onDismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState()
val customProperties = viewModel.editCustomProperties
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
containerColor = Color(0xFF1A1A1A),
contentColor = Color.White
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(bottom = 32.dp)
) {
Text(
text = "水印调整",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(bottom = 16.dp)
)
// Logo 选择
Text(
text = "LOGO",
fontSize = 14.sp,
color = Color.White.copy(alpha = 0.6f),
modifier = Modifier.padding(bottom = 8.dp)
)
val logos = listOf(
"none" to "无",
"apple" to "Apple",
"leica" to "Leica",
"hasselblad" to "Hasselblad",
"sony" to "Sony",
"canon" to "Canon",
"nikon" to "Nikon",
"fujifilm" to "Fujifilm",
"xiaomi" to "Xiaomi",
"huawei" to "Huawei",
"oppo" to "OPPO",
"vivo" to "Vivo"
)
val currentPhoto = viewModel.getCurrentPhoto()
val currentBrand = currentPhoto?.metadata?.brand?.lowercase() ?: ""
val effectiveActiveId =
customProperties["LOGO"] ?: logos.find { it.first != "none" && currentBrand.contains(it.first) }?.first
?: "none"
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(bottom = 16.dp)
) {
items(logos) { (id, name) ->
val isSelected = effectiveActiveId == id
Surface(
onClick = { viewModel.updateEditCustomProperty("LOGO", id) },
color = if (isSelected) AccentOrange.copy(alpha = 0.2f) else Color.White.copy(alpha = 0.1f),
shape = RoundedCornerShape(8.dp),
border = if (isSelected) BorderStroke(1.dp, AccentOrange) else null
) {
Text(
text = name,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
fontSize = 13.sp,
color = if (isSelected) AccentOrange else Color.White
)
}
}
}
// 文字编辑
Text(
text = "文字内容",
fontSize = 14.sp,
color = Color.White.copy(alpha = 0.6f),
modifier = Modifier.padding(bottom = 8.dp)
)
val textTypes = listOf(
TextType.DEVICE_MODEL to "设备型号",
TextType.BRAND to "品牌名称",
TextType.DATE to "日期 (DATE)",
TextType.TIME to "时间 (TIME)",
TextType.DATETIME to "日期时间 (DATETIME)"
)
textTypes.forEach { (type, label) ->
val currentPhoto = viewModel.getCurrentPhoto()
val originalValue = when (type) {
TextType.DEVICE_MODEL -> currentPhoto?.metadata?.deviceModel
TextType.BRAND -> currentPhoto?.metadata?.brand
TextType.DATE -> currentPhoto?.metadata?.dateTaken?.let {
SimpleDateFormat("yyyy.MM.dd", Locale.getDefault()).format(Date(it))
}
TextType.TIME -> currentPhoto?.metadata?.dateTaken?.let {
SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(it))
}
TextType.DATETIME -> currentPhoto?.metadata?.dateTaken?.let {
SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.getDefault()).format(Date(it))
}
else -> null
} ?: ""
OutlinedTextField(
value = customProperties[type.name] ?: originalValue,
onValueChange = { viewModel.updateEditCustomProperty(type.name, it) },
label = { Text(label) },
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = AccentOrange,
unfocusedBorderColor = Color.White.copy(alpha = 0.2f),
focusedLabelColor = AccentOrange,
unfocusedLabelColor = Color.White.copy(alpha = 0.5f),
cursorColor = AccentOrange
),
singleLine = true
)
}
}
}
}
@@ -65,14 +65,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 付费弹窗状态
var showPaymentDialog by mutableStateOf(false)
// 水印编辑弹窗状态
var showWatermarkSheet by mutableStateOf(false)
// 照片列表
private val _photos = MutableStateFlow<List<PhotoData>>(emptyList())
val photos: StateFlow<List<PhotoData>> = _photos.asStateFlow()
// 加载状态
private val _isLoading = MutableStateFlow(false)
val isLoading:StateFlow<Boolean> = _isLoading.asStateFlow()
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
// 分享状态
private val _isSharing = MutableStateFlow(false)
@@ -81,24 +84,24 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 多选模式
var isSelectionMode by mutableStateOf(false)
private set
// 选中的照片
val selectedPhotos = mutableStateListOf<PhotoData>()
// 当前查看的照片索引
var currentPhotoIndex by mutableStateOf(0)
private set
// 编辑状态
var isEditing by mutableStateOf(false)
private set
// 编辑参数
var editRotation by mutableFloatStateOf(0f)
private set
var editBrightness by mutableFloatStateOf(1f)
private set
// LUT 编辑状态
var editLutId: String? by mutableStateOf(null)
private set
@@ -106,25 +109,29 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
var editLutConfig: LutConfig? by mutableStateOf(null)
private set
// 当前照片的元数据
var currentPhotoMetadata: PhotoMetadata? by mutableStateOf(null)
private set
// 可用的 LUT 列表
var availableLuts: List<LutInfo> by mutableStateOf(emptyList())
private set
// 边框编辑状态
var editFrameId: String? by mutableStateOf(null)
private set
var editShowAppBranding by mutableStateOf(true)
private set
// 可用的边框列表
var availableFrames: List<FrameInfo> by mutableStateOf(emptyList())
private set
// 水印自定义属性
var editCustomProperties = mutableStateMapOf<String, String>()
private set
// 最新照片(用于相机界面显示入口)
private val _latestPhoto = MutableStateFlow<PhotoData?>(null)
val latestPhoto: StateFlow<PhotoData?> = _latestPhoto.asStateFlow()
@@ -141,7 +148,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private var pendingDeletePhotos: List<PhotoData> = emptyList()
var batchDeletePendingIntent: android.app.PendingIntent? by mutableStateOf(null)
private set
init {
loadPhotos()
contentRepository.initialize()
@@ -161,7 +168,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 加载照片列表
*/
@@ -173,7 +180,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
try {
// 1. Get basic list from repository (fast: file list only)
val newList = repository.getPhotosSync()
// 2. Reuse existing objects to preserve metadata and avoid UI replacement
val currentPhotos = _photos.value.associateBy { it.id }
val mergedList = newList.map { photo ->
@@ -181,7 +188,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
val context = getApplication<Application>()
// 3. Eagerly load metadata for the first ~30 items (visible area)
val topItemsToLoad = mergedList.take(30).filter { it.metadata == null }
val topItemsLoaded = if (topItemsToLoad.isNotEmpty()) {
@@ -193,17 +200,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}.awaitAll()
}
} else emptyList()
val topMap = topItemsLoaded.associateBy { it.id }
val updatedWithTop = mergedList.map { photo ->
topMap[photo.id] ?: photo
}
// Update UI for the first time
_photos.value = updatedWithTop
_latestPhoto.value = updatedWithTop.firstOrNull()
_isLoading.value = false
// 4. Load the rest of the metadata in background
val remainingToLoad = updatedWithTop.filter { it.metadata == null }
if (remainingToLoad.isNotEmpty()) {
@@ -212,7 +219,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
async { loadSpecificPhotoMetadata(context, photo) }
}.awaitAll()
}
// Final update: merge background results back into the list
val finalMap = fullyUpdatedList.associateBy { it.id }
val finalPhotos = updatedWithTop.map { photo ->
@@ -234,7 +241,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} else {
photo
}
// If dimensions are missing, load from file header
if (updatedPhoto.width == 0 || updatedPhoto.height == 0) {
try {
@@ -243,7 +250,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(photoFile.absolutePath, options)
updatedPhoto = updatedPhoto.copy(width = options.outWidth, height = options.outHeight)
// Cache dimensions back to metadata
val currentMeta = metadata ?: PhotoMetadata()
val newMetadata = currentMeta.copy(width = options.outWidth, height = options.outHeight)
@@ -257,12 +264,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// Already has width/height from metadata
updatedPhoto = updatedPhoto.copy(width = metadata.width, height = metadata.height)
}
// Update the metadata field of the photo object directly? No, copy it.
// The callers (async) will collect these.
return updatedPhoto
}
/**
* 刷新最新照片
*/
@@ -281,7 +288,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} else {
it
}
// If dimensions are missing, load from file (same as loadPhotos)
if (updatedPhoto.width == 0 || updatedPhoto.height == 0) {
try {
@@ -289,7 +296,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(photoFile.absolutePath, options)
updatedPhoto = updatedPhoto.copy(width = options.outWidth, height = options.outHeight)
metadata?.let { m ->
val newMetadata = m.copy(width = options.outWidth, height = options.outHeight)
PhotoManager.saveMetadata(context, it.id, newMetadata)
@@ -308,7 +315,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 加载当前照片的元数据
*/
@@ -317,7 +324,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
val context = getApplication<Application>()
currentPhotoMetadata = PhotoManager.loadMetadata(context, photo.id)
// 更新编辑状态
currentPhotoMetadata?.let { metadata ->
editLutId = metadata.lutId
@@ -326,7 +333,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRotation = metadata.rotation
editFrameId = metadata.frameId
editShowAppBranding = metadata.showAppBranding
// 加载 LUT 配置
editLutId?.let { id ->
editLutConfig = withContext(Dispatchers.IO) {
@@ -362,7 +369,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} else null
}
}
/**
* 进入多选模式
*/
@@ -370,7 +377,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
isSelectionMode = true
selectedPhotos.clear()
}
/**
* 退出多选模式
*/
@@ -378,7 +385,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
isSelectionMode = false
selectedPhotos.clear()
}
/**
* 切换照片选中状态
*/
@@ -388,13 +395,13 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} else {
selectedPhotos.add(photo)
}
// 如果没有选中的照片,退出多选模式
if (selectedPhotos.isEmpty()) {
exitSelectionMode()
}
}
/**
* 全选/取消全选
*/
@@ -406,7 +413,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
selectedPhotos.addAll(_photos.value)
}
}
/**
* 设置当前查看的照片
*/
@@ -414,7 +421,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
currentPhotoIndex = index.coerceIn(0, (_photos.value.size - 1).coerceAtLeast(0))
loadCurrentPhotoMetadata()
}
/**
* 获取当前照片
*/
@@ -674,7 +681,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
PLog.d(TAG, "Batch deleted $deletedCount photos after confirmation")
}
}
/**
* 分享照片
*/
@@ -706,7 +713,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 批量分享选中的照片
*/
@@ -742,7 +749,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 进入编辑模式
*/
@@ -756,6 +763,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRotation = metadata.rotation
editFrameId = metadata.frameId
editShowAppBranding = metadata.showAppBranding
editCustomProperties.clear()
editCustomProperties.putAll(metadata.customProperties)
} ?: run {
editLutId = null
editLutIntensity = 1f
@@ -763,8 +772,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRotation = 0f
editFrameId = null
editShowAppBranding = true
editCustomProperties.clear()
}
// 加载当前编辑的 LUT 配置
editLutId?.let { id ->
viewModelScope.launch {
@@ -774,7 +784,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 退出编辑模式
*/
@@ -787,22 +797,23 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editLutConfig = null
editFrameId = null
editShowAppBranding = true
editCustomProperties.clear()
}
/**
* 旋转90度
*/
fun rotate90() {
editRotation = (editRotation + 90f) % 360f
}
/**
* 设置亮度
*/
fun setBrightness(value: Float) {
editBrightness = value.coerceIn(0.5f, 2f)
}
/**
* 设置 LUT
*/
@@ -812,35 +823,42 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editLutConfig = null
return
}
viewModelScope.launch {
editLutConfig = withContext(Dispatchers.IO) {
contentRepository.lutManager.loadLut(lutId)
}
}
}
/**
* 设置 LUT 强度
*/
fun updateEditLutIntensity(intensity: Float) {
editLutIntensity = intensity.coerceIn(0f, 1f)
}
/**
* 设置边框
*/
fun setEditFrame(frameId: String?) {
editFrameId = frameId
}
/**
* 设置是否显示 App 品牌
*/
fun setShowAppBranding(show: Boolean) {
editShowAppBranding = show
}
/**
* 更新水印自定义属性
*/
fun updateEditCustomProperty(key: String, value: String) {
editCustomProperties[key] = value
}
/**
* 获取指定照片的完整转换器(LUT + 边框)
*/
@@ -853,6 +871,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
photoProcessor = photoProcessor
)
}
/**
* 获取应用 LUT 和边框后的预览 Bitmap
*/
@@ -863,18 +882,19 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val inputStream = context.contentResolver.openInputStream(photo.previewUri)
val bitmap = BitmapFactory.decodeStream(inputStream)
inputStream?.close()
if (bitmap == null) return@withContext null
val metadata = (photo.metadata ?: PhotoMetadata()).copy(
lutId = editLutId,
lutIntensity = editLutIntensity,
brightness = editBrightness,
rotation = editRotation,
frameId = editFrameId,
showAppBranding = editShowAppBranding
showAppBranding = editShowAppBranding,
customProperties = editCustomProperties.toMap()
)
photoProcessor.process(context, bitmap, metadata, photo.previewUri)
} catch (e: Exception) {
PLog.e(TAG, "Failed to create preview", e)
@@ -882,7 +902,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 保存编辑(只更新元数据,不修改原图)
*/
@@ -904,13 +924,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
brightness = editBrightness,
rotation = editRotation,
frameId = editFrameId,
showAppBranding = editShowAppBranding
showAppBranding = editShowAppBranding,
customProperties = editCustomProperties.toMap()
)
val success = PhotoManager.saveMetadata(context, photo.id, metadata)
if (success) {
currentPhotoMetadata = metadata
// 更新 photos 列表中对应照片的 metadata,触发 UI 刷新
val updatedPhotos = _photos.value.map { p ->
if (p.id == photo.id) {
@@ -920,12 +941,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
_photos.value = updatedPhotos
// 同步更新 latestPhoto
if (_latestPhoto.value?.id == photo.id) {
_latestPhoto.value = _latestPhoto.value?.copy(metadata = metadata)
}
exitEditMode()
}
onComplete(success)
@@ -935,7 +956,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
/**
* 保存编辑(导出烘焙后的图片)
*/
@@ -953,7 +974,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
brightness = editBrightness,
rotation = editRotation,
frameId = editFrameId,
showAppBranding = editShowAppBranding
showAppBranding = editShowAppBranding,
customProperties = editCustomProperties.toMap()
)
exportPhotoInternal(
photo = photo,
@@ -1047,7 +1069,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val processedBitmap = photoProcessor.process(context, bitmap, metadata, photo.uri)
// 保存到指定目录
val filename = "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}$filenameSuffix.jpg"
val filename =
"PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}$filenameSuffix.jpg"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
@@ -1130,7 +1153,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
}
override fun onCleared() {
super.onCleared()
lutImageProcessor.release()