426 lines
17 KiB
Kotlin
426 lines
17 KiB
Kotlin
|
|
package com.shitoucuo.postpad
|
|||
|
|
|
|||
|
|
import android.content.Context
|
|||
|
|
import android.content.Intent
|
|||
|
|
import android.graphics.Bitmap
|
|||
|
|
import android.graphics.BitmapFactory
|
|||
|
|
import android.graphics.Color
|
|||
|
|
import android.graphics.Matrix
|
|||
|
|
import android.graphics.RectF
|
|||
|
|
import android.net.Uri
|
|||
|
|
import android.os.Bundle
|
|||
|
|
import android.util.TypedValue
|
|||
|
|
import android.view.GestureDetector
|
|||
|
|
import android.view.Gravity
|
|||
|
|
import android.view.MotionEvent
|
|||
|
|
import android.view.ScaleGestureDetector
|
|||
|
|
import android.view.View
|
|||
|
|
import android.view.ViewGroup
|
|||
|
|
import android.widget.FrameLayout
|
|||
|
|
import android.widget.ProgressBar
|
|||
|
|
import android.widget.TextView
|
|||
|
|
import androidx.appcompat.app.AppCompatActivity
|
|||
|
|
import androidx.lifecycle.lifecycleScope
|
|||
|
|
import kotlinx.coroutines.Dispatchers
|
|||
|
|
import kotlinx.coroutines.launch
|
|||
|
|
import kotlinx.coroutines.withContext
|
|||
|
|
import okhttp3.Request
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 大图预览:黑底、双指缩放、放大后单指拖动、双击在「适应屏幕 / 2.5 倍」之间切换,
|
|||
|
|
* 单击图片或点右上角 × 退出。
|
|||
|
|
*
|
|||
|
|
* 界面用代码搭建:整页只有一张图和两个状态提示,写成布局文件反而多几个文件要维护。
|
|||
|
|
*
|
|||
|
|
* 取图分三层,任何一层成功就显示,避免"点开只剩一行加载失败":
|
|||
|
|
* 1. [ImageMemoryCache]:卡片上那张图已经解码在内存里,点开立即显示;
|
|||
|
|
* 2. 原图下载:[Http.imageClient] 与列表共用 64MB 磁盘缓存,列表里下过的图直接命中;
|
|||
|
|
* 3. 地址归一化 + 退一步的请求头(浏览器 UA + Referer):正文里手写的图片地址
|
|||
|
|
* 常带 `<…>`、`&`、相对路径、空格,或图床按 Referer 防盗链,直接请求会失败。
|
|||
|
|
*/
|
|||
|
|
class ImagePreviewActivity : AppCompatActivity() {
|
|||
|
|
|
|||
|
|
companion object {
|
|||
|
|
private const val EXTRA_URL = "url"
|
|||
|
|
|
|||
|
|
fun intent(context: Context, url: String): Intent =
|
|||
|
|
Intent(context, ImagePreviewActivity::class.java).putExtra(EXTRA_URL, url)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private lateinit var imageView: ZoomableImageView
|
|||
|
|
private lateinit var progress: ProgressBar
|
|||
|
|
private lateinit var errorView: TextView
|
|||
|
|
|
|||
|
|
/** 原始地址(点卡片传过来的)与归一化后用于请求的地址 */
|
|||
|
|
private var rawUrl: String = ""
|
|||
|
|
private var url: String = ""
|
|||
|
|
|
|||
|
|
/** 当前正在显示的位图:用来判断原图是否比兜底图更清晰 */
|
|||
|
|
private var shown: Bitmap? = null
|
|||
|
|
|
|||
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|||
|
|
super.onCreate(savedInstanceState)
|
|||
|
|
rawUrl = intent.getStringExtra(EXTRA_URL).orEmpty().trim()
|
|||
|
|
if (rawUrl.isBlank()) {
|
|||
|
|
finish()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
url = ImageUrl.normalize(this, rawUrl)
|
|||
|
|
|
|||
|
|
// 看图页固定黑底,状态栏与导航栏一并压黑,避免白边割裂画面
|
|||
|
|
window.statusBarColor = Color.BLACK
|
|||
|
|
window.navigationBarColor = Color.BLACK
|
|||
|
|
|
|||
|
|
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
|||
|
|
|
|||
|
|
imageView = ZoomableImageView(this).apply {
|
|||
|
|
layoutParams = FrameLayout.LayoutParams(
|
|||
|
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
|||
|
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
|||
|
|
)
|
|||
|
|
onSingleTap = { finish() }
|
|||
|
|
visibility = View.INVISIBLE
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
progress = ProgressBar(this).apply {
|
|||
|
|
layoutParams = FrameLayout.LayoutParams(dp(36), dp(36), Gravity.CENTER)
|
|||
|
|
indeterminateDrawable?.setTint(Color.WHITE)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
errorView = TextView(this).apply {
|
|||
|
|
setTextColor(Color.WHITE)
|
|||
|
|
setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
|
|||
|
|
gravity = Gravity.CENTER
|
|||
|
|
setPadding(dp(24), dp(16), dp(24), dp(16))
|
|||
|
|
layoutParams = FrameLayout.LayoutParams(
|
|||
|
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
|||
|
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
|||
|
|
Gravity.CENTER,
|
|||
|
|
)
|
|||
|
|
visibility = View.GONE
|
|||
|
|
setOnClickListener { load() }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
val close = TextView(this).apply {
|
|||
|
|
text = getString(R.string.image_preview_close_glyph)
|
|||
|
|
contentDescription = getString(R.string.image_preview_close)
|
|||
|
|
setTextColor(Color.WHITE)
|
|||
|
|
setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
|
|||
|
|
gravity = Gravity.CENTER
|
|||
|
|
setPadding(dp(16), dp(10), dp(16), dp(10))
|
|||
|
|
layoutParams = FrameLayout.LayoutParams(
|
|||
|
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
|||
|
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
|||
|
|
Gravity.TOP or Gravity.END,
|
|||
|
|
).apply {
|
|||
|
|
topMargin = dp(28)
|
|||
|
|
rightMargin = dp(10)
|
|||
|
|
}
|
|||
|
|
setOnClickListener { finish() }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
root.addView(imageView)
|
|||
|
|
root.addView(progress)
|
|||
|
|
root.addView(errorView)
|
|||
|
|
root.addView(close)
|
|||
|
|
setContentView(root)
|
|||
|
|
|
|||
|
|
load()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun load() {
|
|||
|
|
// 第一层:卡片里已经解码好的那张,先摆上去,用户点开立刻有画面
|
|||
|
|
val fallback = ImageMemoryCache.get(url) ?: ImageMemoryCache.get(rawUrl)
|
|||
|
|
if (fallback != null) {
|
|||
|
|
show(fallback)
|
|||
|
|
progress.visibility = View.GONE
|
|||
|
|
} else {
|
|||
|
|
progress.visibility = View.VISIBLE
|
|||
|
|
errorView.visibility = View.GONE
|
|||
|
|
imageView.visibility = View.INVISIBLE
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
lifecycleScope.launch {
|
|||
|
|
val result = withContext(Dispatchers.IO) { runCatching { fetch(url) } }
|
|||
|
|
if (isFinishing || isDestroyed) return@launch
|
|||
|
|
progress.visibility = View.GONE
|
|||
|
|
val bitmap = result.getOrNull()
|
|||
|
|
if (bitmap != null) {
|
|||
|
|
val current = shown
|
|||
|
|
// 兜底图已经显示时,只在原图更清晰、且用户还没开始缩放的情况下替换,
|
|||
|
|
// 否则会把正在看的位置与缩放比例重置掉
|
|||
|
|
val sharper = current == null || bitmap.byteCount > current.byteCount
|
|||
|
|
if (current == null || (sharper && !imageView.transformed)) {
|
|||
|
|
show(bitmap)
|
|||
|
|
}
|
|||
|
|
ImageMemoryCache.put(url, bitmap)
|
|||
|
|
errorView.visibility = View.GONE
|
|||
|
|
} else if (shown == null) {
|
|||
|
|
val reason = result.exceptionOrNull()?.message.orEmpty()
|
|||
|
|
errorView.text = if (reason.isBlank()) {
|
|||
|
|
getString(R.string.image_preview_failed)
|
|||
|
|
} else {
|
|||
|
|
getString(R.string.image_preview_failed) + "\n" + reason
|
|||
|
|
}
|
|||
|
|
errorView.visibility = View.VISIBLE
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun show(bitmap: Bitmap) {
|
|||
|
|
shown = bitmap
|
|||
|
|
imageView.visibility = View.VISIBLE
|
|||
|
|
imageView.setBitmap(bitmap)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 下载并按目标尺寸采样解码,避免几千万像素的原图直接 OOM */
|
|||
|
|
private fun fetch(address: String): Bitmap {
|
|||
|
|
val bytes = fetchBytes(address)
|
|||
|
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
|||
|
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
|||
|
|
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
|||
|
|
throw IllegalStateException("图片内容无法解析(可能被拦截或已失效)")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
val metrics = resources.displayMetrics
|
|||
|
|
// 采样目标是屏幕长边:保证放大时仍有细节,同时把内存压在十几 MB 以内
|
|||
|
|
val target = maxOf(metrics.widthPixels, metrics.heightPixels)
|
|||
|
|
val options = BitmapFactory.Options().apply {
|
|||
|
|
inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, target)
|
|||
|
|
inPreferredConfig = Bitmap.Config.ARGB_8888
|
|||
|
|
}
|
|||
|
|
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
|||
|
|
?: throw IllegalStateException("图片解码失败")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 取原始字节。失败时抛出带原因的消息(直接显示给用户,便于对症下药):
|
|||
|
|
* - `data:` / `content:` / `file:` 走本地解析;
|
|||
|
|
* - http(s) 先按普通请求,失败再换浏览器 UA + Referer 重试一次(防盗链最常见的拦法)。
|
|||
|
|
*/
|
|||
|
|
private fun fetchBytes(address: String): ByteArray {
|
|||
|
|
if (address.startsWith("data:", true)) return dataUriBytes(address)
|
|||
|
|
if (address.startsWith("content://") || address.startsWith("file://")) {
|
|||
|
|
return contentResolver.openInputStream(Uri.parse(address))?.use { it.readBytes() }
|
|||
|
|
?: throw IllegalStateException("读不到本地图片")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var reason = "图片地址无效:$address"
|
|||
|
|
for (attempt in 0 until 2) {
|
|||
|
|
val request = Request.Builder()
|
|||
|
|
.url(address)
|
|||
|
|
.header("Accept", "image/*,*/*;q=0.8")
|
|||
|
|
.apply {
|
|||
|
|
if (attempt == 0) {
|
|||
|
|
header("User-Agent", "PostPad")
|
|||
|
|
} else {
|
|||
|
|
header("User-Agent", RssApi.UA_BROWSER)
|
|||
|
|
refererOf(address)?.let { header("Referer", it) }
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
.build()
|
|||
|
|
try {
|
|||
|
|
Http.imageClient(this).newCall(request).execute().use { response ->
|
|||
|
|
if (!response.isSuccessful) {
|
|||
|
|
reason = "HTTP ${response.code}"
|
|||
|
|
return@use
|
|||
|
|
}
|
|||
|
|
val type = response.header("Content-Type").orEmpty().lowercase()
|
|||
|
|
if (type.startsWith("text/") || type.contains("html")) {
|
|||
|
|
reason = "服务器返回的是网页($type)"
|
|||
|
|
return@use
|
|||
|
|
}
|
|||
|
|
val body = response.body ?: run {
|
|||
|
|
reason = "响应为空"
|
|||
|
|
return@use
|
|||
|
|
}
|
|||
|
|
// inline use:这里是直接返回整个函数的字节
|
|||
|
|
return body.bytes()
|
|||
|
|
}
|
|||
|
|
} catch (e: Exception) {
|
|||
|
|
reason = e.message ?: e.javaClass.simpleName
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
throw IllegalStateException(reason)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** data:image/png;base64,… 这类内联图片 */
|
|||
|
|
private fun dataUriBytes(uri: String): ByteArray {
|
|||
|
|
val comma = uri.indexOf(',')
|
|||
|
|
if (comma < 0) throw IllegalStateException("内联图片地址无效")
|
|||
|
|
val meta = uri.substring(5, comma)
|
|||
|
|
val payload = uri.substring(comma + 1)
|
|||
|
|
return if (meta.contains("base64", true)) {
|
|||
|
|
android.util.Base64.decode(payload, android.util.Base64.DEFAULT)
|
|||
|
|
} else {
|
|||
|
|
java.net.URLDecoder.decode(payload, "UTF-8").toByteArray()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 防盗链常校验 Referer:取图片所在站点的根地址 */
|
|||
|
|
private fun refererOf(address: String): String? = runCatching {
|
|||
|
|
val parsed = java.net.URL(address)
|
|||
|
|
val host = parsed.host ?: return@runCatching null
|
|||
|
|
"${parsed.protocol}://$host/"
|
|||
|
|
}.getOrNull()
|
|||
|
|
|
|||
|
|
private fun sampleSize(width: Int, height: Int, target: Int): Int {
|
|||
|
|
var sample = 1
|
|||
|
|
while (width / (sample * 2) >= target && height / (sample * 2) >= target) {
|
|||
|
|
sample *= 2
|
|||
|
|
}
|
|||
|
|
return sample
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 简易可缩放图片:只依赖 Matrix 与系统手势检测器,不引第三方手势库。
|
|||
|
|
* 缩放范围从「适应屏幕」到其 4 倍;放大后单指拖动,松手时把图拉回可视区域。
|
|||
|
|
*/
|
|||
|
|
private class ZoomableImageView(context: Context) :
|
|||
|
|
androidx.appcompat.widget.AppCompatImageView(context) {
|
|||
|
|
|
|||
|
|
var onSingleTap: (() -> Unit)? = null
|
|||
|
|
|
|||
|
|
private val transform = Matrix()
|
|||
|
|
private var baseScale = 1f
|
|||
|
|
private var currentScale = 1f
|
|||
|
|
private var lastX = 0f
|
|||
|
|
private var lastY = 0f
|
|||
|
|
private var multiTouch = false
|
|||
|
|
|
|||
|
|
/** 用户是否缩放/拖动过:用于决定原图到达时要不要替换画面 */
|
|||
|
|
var transformed = false
|
|||
|
|
private set
|
|||
|
|
|
|||
|
|
private val scaleDetector = ScaleGestureDetector(
|
|||
|
|
context,
|
|||
|
|
object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
|||
|
|
override fun onScale(detector: ScaleGestureDetector): Boolean {
|
|||
|
|
applyScale(currentScale * detector.scaleFactor, detector.focusX, detector.focusY)
|
|||
|
|
return true
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
private val tapDetector = GestureDetector(
|
|||
|
|
context,
|
|||
|
|
object : GestureDetector.SimpleOnGestureListener() {
|
|||
|
|
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
|
|||
|
|
// 双指缩放结束后系统仍可能补一个单击,这里挡掉,避免缩放完直接被关掉
|
|||
|
|
if (!multiTouch) onSingleTap?.invoke()
|
|||
|
|
return true
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
override fun onDoubleTap(e: MotionEvent): Boolean {
|
|||
|
|
val target = if (currentScale > baseScale * 1.5f) baseScale else baseScale * 2.5f
|
|||
|
|
applyScale(target, e.x, e.y)
|
|||
|
|
return true
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
init {
|
|||
|
|
scaleType = ScaleType.MATRIX
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
fun setBitmap(bitmap: Bitmap) {
|
|||
|
|
transformed = false
|
|||
|
|
setImageBitmap(bitmap)
|
|||
|
|
// 等一帧再算:此刻 width/height 可能还是 0
|
|||
|
|
post { fitToView() }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
|||
|
|
super.onSizeChanged(w, h, oldw, oldh)
|
|||
|
|
if (drawable != null) fitToView()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 按控件尺寸等比缩放并居中,作为缩放下限 */
|
|||
|
|
private fun fitToView() {
|
|||
|
|
val d = drawable ?: return
|
|||
|
|
val viewW = width.toFloat()
|
|||
|
|
val viewH = height.toFloat()
|
|||
|
|
val imageW = d.intrinsicWidth.toFloat()
|
|||
|
|
val imageH = d.intrinsicHeight.toFloat()
|
|||
|
|
if (viewW <= 0f || viewH <= 0f || imageW <= 0f || imageH <= 0f) return
|
|||
|
|
|
|||
|
|
val scale = minOf(viewW / imageW, viewH / imageH)
|
|||
|
|
baseScale = scale
|
|||
|
|
currentScale = scale
|
|||
|
|
transform.reset()
|
|||
|
|
transform.postScale(scale, scale)
|
|||
|
|
transform.postTranslate((viewW - imageW * scale) / 2f, (viewH - imageH * scale) / 2f)
|
|||
|
|
imageMatrix = transform
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private fun applyScale(target: Float, focusX: Float, focusY: Float) {
|
|||
|
|
if (currentScale <= 0f) return
|
|||
|
|
val clamped = target.coerceIn(baseScale, baseScale * 4f)
|
|||
|
|
val factor = clamped / currentScale
|
|||
|
|
if (factor == 1f) {
|
|||
|
|
// 已经到边界:回弹到初始状态,避免反复缩放积累误差
|
|||
|
|
if (clamped <= baseScale) fitToView()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
if (clamped != baseScale) transformed = true
|
|||
|
|
currentScale = clamped
|
|||
|
|
transform.postScale(factor, factor, focusX, focusY)
|
|||
|
|
imageMatrix = transform
|
|||
|
|
if (clamped <= baseScale) fitToView()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|||
|
|
scaleDetector.onTouchEvent(event)
|
|||
|
|
tapDetector.onTouchEvent(event)
|
|||
|
|
when (event.actionMasked) {
|
|||
|
|
MotionEvent.ACTION_DOWN -> {
|
|||
|
|
multiTouch = false
|
|||
|
|
lastX = event.x
|
|||
|
|
lastY = event.y
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
MotionEvent.ACTION_POINTER_DOWN -> {
|
|||
|
|
multiTouch = true
|
|||
|
|
transformed = true
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
MotionEvent.ACTION_MOVE -> {
|
|||
|
|
if (!scaleDetector.isInProgress && currentScale > baseScale) {
|
|||
|
|
transform.postTranslate(event.x - lastX, event.y - lastY)
|
|||
|
|
imageMatrix = transform
|
|||
|
|
lastX = event.x
|
|||
|
|
lastY = event.y
|
|||
|
|
transformed = true
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> settle()
|
|||
|
|
}
|
|||
|
|
return true
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 松手后把图片拉回可视范围,避免拖出屏幕后找不回来 */
|
|||
|
|
private fun settle() {
|
|||
|
|
val d = drawable ?: return
|
|||
|
|
val rect = RectF(0f, 0f, d.intrinsicWidth.toFloat(), d.intrinsicHeight.toFloat())
|
|||
|
|
transform.mapRect(rect)
|
|||
|
|
val viewW = width.toFloat()
|
|||
|
|
val viewH = height.toFloat()
|
|||
|
|
var dx = 0f
|
|||
|
|
var dy = 0f
|
|||
|
|
if (rect.width() <= viewW) dx = (viewW - rect.width()) / 2f - rect.left
|
|||
|
|
else if (rect.left > 0f) dx = -rect.left
|
|||
|
|
else if (rect.right < viewW) dx = viewW - rect.right
|
|||
|
|
if (rect.height() <= viewH) dy = (viewH - rect.height()) / 2f - rect.top
|
|||
|
|
else if (rect.top > 0f) dy = -rect.top
|
|||
|
|
else if (rect.bottom < viewH) dy = viewH - rect.bottom
|
|||
|
|
if (dx != 0f || dy != 0f) {
|
|||
|
|
transform.postTranslate(dx, dy)
|
|||
|
|
imageMatrix = transform
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|