Palette始终生成空Swatch,如何正确用它生成适配背景的文字颜色?
问题:Palette处理纯色背景Bitmap时始终返回空Swatch
我想要创建一个任意背景色的Bitmap并在其上绘制标题,且无法提前知晓背景色。尝试使用Palette根据背景色生成标题文字颜色,但Palette始终生成空Swatch。
我的代码:
bmpImage = Bitmap.createBitmap(1130, 842, Bitmap.Config.ARGB_8888); canvas = new Canvas(bmpImage); canvas.drawColor(backgroundColor); Palette.from(bmpImage).generate(new Palette.PaletteAsyncListener() { @Override public void onGenerated(@Nullable Palette palette) { List<Palette.Swatch> s = palette.getSwatches(); int x = palette.getDominantColor(0);//<-- 始终返回0 Log.d(TAG,"Swatches size"+s.size());//<-- 始终返回0 Palette.Swatch vibrantSwatch = palette.getVibrantSwatch(); if(vibrantSwatch!=null) {// <-- 此处始终为null paint.setColor(vibrantSwatch.getBodyTextColor()); canvas.drawText(setTitle, textX, textY, paint); } } });
我的Bitmap是正常的,通过bmpImage.compress(Bitmap.CompressFormat.PNG, 100, outpStream);可成功保存图片。
Gradle依赖:implementation 'androidx.palette:palette:1.0.0'
请问如何正确使用Palette?
解决方案
核心原因
Palette默认的色彩采样算法会过滤掉单一纯色的Bitmap,它认为这种场景没有足够的色彩多样性来生成有意义的Swatch,因此返回空结果。针对纯色背景的需求,有两种处理方式:
方式一:直接计算文字颜色(推荐)
不需要依赖Palette,通过计算背景色的亮度选择对比明显的文字颜色,符合WCAG无障碍标准,高效且准确:
// 计算背景色的亮度值 float luminance = 0.299f * Color.red(backgroundColor) + 0.587f * Color.green(backgroundColor) + 0.114f * Color.blue(backgroundColor); // 亮背景用黑色,暗背景用白色 int textColor = luminance > 128 ? Color.BLACK : Color.WHITE; // 绘制标题 paint.setColor(textColor); canvas.drawText(setTitle, textX, textY, paint);
方式二:强制Palette处理纯色Bitmap
如果一定要用Palette,可以通过Palette.Builder调整参数,强制生成Swatch:
Palette.from(bmpImage) .minimumColorCount(1) // 设置最小颜色采样数量为1 .generate(new Palette.PaletteAsyncListener() { @Override public void onGenerated(@Nullable Palette palette) { if (palette == null) return; Palette.Swatch dominantSwatch = palette.getDominantSwatch(); if (dominantSwatch != null) { paint.setColor(dominantSwatch.getBodyTextColor()); canvas.drawText(setTitle, textX, textY, paint); } } });
注意事项
- 纯色背景场景下,方式一的性能和准确性都优于方式二,Palette的异步生成会带来额外线程开销。
- 若背景是渐变、复杂图案这类多色彩场景,再使用Palette默认逻辑提取色彩。
内容的提问来源于stack exchange,提问作者Alex Mads
相关产品推荐
相关产品推荐

