|
| 1 | +package com.threegap.bitnagil.presentation.util.statusbar |
| 2 | + |
| 3 | +import android.graphics.Bitmap |
| 4 | +import android.graphics.Color |
| 5 | +import android.graphics.Rect |
| 6 | +import android.os.Handler |
| 7 | +import android.os.Looper |
| 8 | +import android.view.PixelCopy |
| 9 | +import android.view.Window |
| 10 | +import androidx.core.graphics.createBitmap |
| 11 | +import androidx.core.view.ViewCompat |
| 12 | +import androidx.core.view.WindowInsetsCompat |
| 13 | +import androidx.core.graphics.get |
| 14 | +import androidx.core.view.WindowInsetsControllerCompat |
| 15 | + |
| 16 | +object StatusBarAppearanceManager { |
| 17 | + private const val LUMINANCE_THRESHOLD = 150 |
| 18 | + |
| 19 | + fun applyStatusBarColorByLuminance(window: Window) { |
| 20 | + val height = getStatusBarHeight(window = window) |
| 21 | + if (height <= 0) return |
| 22 | + |
| 23 | + captureStatusBarBitmap( |
| 24 | + window = window, |
| 25 | + height = height, |
| 26 | + ) { bmp -> |
| 27 | + bmp?.let { |
| 28 | + val lum = calculateLuminance(it) |
| 29 | + WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars = (lum > LUMINANCE_THRESHOLD) |
| 30 | + it.recycle() |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + private fun getStatusBarHeight(window: Window): Int { |
| 36 | + val decorView = window.decorView |
| 37 | + val insets = ViewCompat.getRootWindowInsets(decorView) |
| 38 | + return insets?.getInsets(WindowInsetsCompat.Type.statusBars())?.top ?: 0 |
| 39 | + } |
| 40 | + |
| 41 | + private fun captureStatusBarBitmap( |
| 42 | + window: Window, |
| 43 | + height: Int, |
| 44 | + onResult: (Bitmap?) -> Unit |
| 45 | + ) { |
| 46 | + val width = window.decorView.width |
| 47 | + if (width <= 0) { |
| 48 | + onResult(null) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + val rect = Rect(0, 0, window.decorView.width, height) |
| 53 | + val bmp = createBitmap(rect.width(), rect.height()) |
| 54 | + |
| 55 | + try { |
| 56 | + PixelCopy.request(window, rect, bmp, { result -> |
| 57 | + if (result == PixelCopy.SUCCESS) { |
| 58 | + onResult(bmp) |
| 59 | + } else { |
| 60 | + bmp.recycle() |
| 61 | + onResult(null) |
| 62 | + } |
| 63 | + }, Handler(Looper.getMainLooper())) |
| 64 | + } catch (_: Exception) { |
| 65 | + bmp.recycle() |
| 66 | + onResult(null) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private fun calculateLuminance(bitmap: Bitmap): Int { |
| 71 | + val x = bitmap.width / 2 |
| 72 | + val y = bitmap.height / 2 |
| 73 | + val px = bitmap[x, y] |
| 74 | + return (0.299 * Color.red(px) + 0.587 * Color.green(px) + 0.114 * Color.blue(px)).toInt() |
| 75 | + } |
| 76 | +} |
0 commit comments