检测是否为黑暗模式
fun Context.isNightMode() = with(this) {
resources.configuration.uiModeand Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
Color 适配
直接在 res 目录下再新建一个 values-night/colors.xml 目录文件,与国际化适配方式一致。
![](https://img.haomeiwen.com/i11302108/65309ef989318e92.png)
图片适配
1. 同 Color,创建对应的 drawable-night 目录,将黑暗模式对应的图片放在里面
2. 灰阶颜色反转
/**
* 反转灰阶颜色
* @param isRecycle 是否将原 bitmap 回收
* @param chromatism 色差值
*/
fun Bitmap.reverseGray(isRecycle: Boolean = true, chromatism:Int = 18):Bitmap {
var count= 0
val mArrayColorLength:Int = width * height
val mArrayColor= IntArray(mArrayColorLength)
val bitmapW:Int = width
val bitmapH:Int = height
for (iin 0 until height) {
for (jin 0 until width) {
// 获得 Bitmap 中每一个点的 color 颜色值
var color= getPixel(j, i)
// 将颜色值存在一个数组中 方便后面修改
// mArrayColor[count] = color;
var r:Int = color.red
var g:Int = color.green
var b:Int = color.blue
if (maxOf(r, g, b) - minOf(r, g, b) < chromatism) {
r= 255 - r
g= 255 - g
b= 255 - b
}
color= Color.argb(color.alpha, r, g, b)
mArrayColor[count] = color
count++
}
}
if (isRecycle) { recycle()}
return Bitmap.createBitmap(mArrayColor, bitmapW, bitmapH, config)
}
使用(视图使用 AnKo):在 applyRecursively 方法中
applyRecursively {
when (it) {
is TextView -> {
if (ctx.isNightMode() && !it.compoundDrawables.isNullOrEmpty()) {
val drawableList= arrayListOf<Drawable?>(null, null, null, null)
it.compoundDrawables.forEachIndexed { index, drawable ->
if (drawable != null && drawable is BitmapDrawable) {
drawableList[index] =
drawable.bitmap.reverseGray(false).toDrawable(ctx.resources)
} else {
drawableList[index] = drawable
}
}
it.setCompoundDrawablesWithIntrinsicBounds(
drawableList[0], drawableList[1], drawableList[2], drawableList[3]
)
}
}
is ImageView -> {
if (it.tag != tagReallyImage&& ctx.isNightMode()) {
it.post {
// 此处不知道什么原因,如果它的 layoutParams 宽高设置为 wrapContent 时,会显示不出,以后知道原因了会写明,有朋友知道的话也请留言告知,感谢。
val lp = it.layoutParams
it.layoutParams = ViewGroup.MarginLayoutParams(matchParent, matchParent)
it.imageBitmap = it.toBitmap()?.reverseGray()
it.layoutParams = lp
// toBitmap 方法看这 View 的一些扩展方法
}
}
}
}
}
全局黑白化(转自鸿洋大神的一篇公众文)
val paint= Paint()
val cm= ColorMatrix()
cm.setSaturation(0f)
paint.colorFilter = ColorMatrixColorFilter(cm)
window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
网友评论