Android Jetpack:利用Palette进行图片取色

news2024/9/24 15:19:00

与产品MM那些事

新来一个产品MM,因为比较平,我们就叫她A妹吧。A妹来第一天就指出:页面顶部的Banner广告位的背景是白色的,太单调啦,人家不喜欢啦,需要根据广告图片的内容自动切换背景颜色,颜色要与广告图主色调一致。作为一名合格的码农我直接回绝了,我说咱们的应用主打简洁,整这花里胡哨的干嘛,劳民伤财。A妹也没放弃,与我深入交流了一夜成功说服了我。

其实要实现这个需求也不难,Google已经为我们提供了一个方便的工具————Palette。

前言

Palette即调色板这个功能其实很早就发布了,Jetpack同样将这个功能也纳入其中,想要使用这个功能,需要先依赖库

implementation 'androidx.palette:palette:1.0.0'

本篇文章就来讲解一下如何使用Palette在图片中提取颜色。

创建Palette

创建Palette其实很简单,如下

var builder = Palette.from(bitmap)
var palette = builder.generate()

这样,我们就通过一个Bitmap创建一个Pallete对象。

注意:直接使用Palette.generate(bitmap)也可以,但是这个方法已经不推荐使用了,网上很多老文章中依然使用这种方式。建议还是使用Palette.Builder这种方式。

generate()这个函数是同步的,当然考虑图片处理可能比较耗时,Android同时提供了异步函数

public AsyncTask<Bitmap, Void, Palette> generate(
        @NonNull final PaletteAsyncListener listener) {

通过一个PaletteAsyncListener来获取Palette实例,这个接口如下:

public interface PaletteAsyncListener {
    /**
     * Called when the {@link Palette} has been generated. {@code null} will be passed when an
     * error occurred during generation.
     */
    void onGenerated(@Nullable Palette palette);
}

提取颜色

有了Palette实例,就可以通过Palette对象的相应函数就可以获取图片中的颜色,而且不只一种颜色,下面一一列举:

  • getDominantColor:获取图片中的主色调
  • getMutedColor:获取图片中柔和的颜色
  • getDarkMutedColor:获取图片中柔和的暗色
  • getLightMutedColor:获取图片中柔和的亮色
  • getVibrantColor:获取图片中有活力的颜色
  • getDarkVibrantColor:获取图片中有活力的暗色
  • getLightVibrantColor:获取图片中有活力的亮色

这些函数都需要提供一个默认颜色,如果这个颜色Swatch无效则使用这个默认颜色。光这么说不直观,我们来测试一下,代码如下:

var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.a)
var builder = Palette.from(bitmap)
var palette = builder.generate()
color0.setBackgroundColor(palette.getDominantColor(Color.WHITE))
color1.setBackgroundColor(palette.getMutedColor(Color.WHITE))
color2.setBackgroundColor(palette.getDarkMutedColor(Color.WHITE))
color3.setBackgroundColor(palette.getLightMutedColor(Color.WHITE))
color4.setBackgroundColor(palette.getVibrantColor(Color.WHITE))
color5.setBackgroundColor(palette.getDarkVibrantColor(Color.WHITE))
color6.setBackgroundColor(palette.getLightVibrantColor(Color.WHITE))

运行后结果如下:

111.jpg

这样各个颜色的差别就一目了然。除了上面的函数,还可以使用getColorForTarget这个函数,如下:

@ColorInt
public int getColorForTarget(@NonNull final Target target, @ColorInt final int defaultColor) {

这个函数需要一个Target,提供了6个静态字段,如下:

/**
 * A target which has the characteristics of a vibrant color which is light in luminance.
*/
public static final Target LIGHT_VIBRANT;

/**
 * A target which has the characteristics of a vibrant color which is neither light or dark.
 */
public static final Target VIBRANT;

/**
 * A target which has the characteristics of a vibrant color which is dark in luminance.
 */
public static final Target DARK_VIBRANT;

/**
 * A target which has the characteristics of a muted color which is light in luminance.
 */
public static final Target LIGHT_MUTED;

/**
 * A target which has the characteristics of a muted color which is neither light or dark.
 */
public static final Target MUTED;

/**
 * A target which has the characteristics of a muted color which is dark in luminance.
 */
public static final Target DARK_MUTED;

其实就是对应着上面除了主色调之外的六种颜色。

文字颜色自动适配

在上面的运行结果中可以看到,每个颜色上面的文字都很清楚的显示,而且它们并不是同一种颜色。其实这也是Palette提供的功能。

通过下面的函数,我们可以得到各种色调所对应的Swatch对象:

  • getDominantSwatch
  • getMutedSwatch
  • getDarkMutedSwatch
  • getLightMutedSwatch
  • getVibrantSwatch
  • getDarkVibrantSwatch
  • getLightVibrantSwatch

注意:同上面一样,也可以通过getSwatchForTarget(@NonNull final Target target)来获取

Swatch类提供了以下函数:

  • getPopulation(): 样本中的像素数量
  • getRgb(): 颜色的RBG值
  • getHsl(): 颜色的HSL值
  • getBodyTextColor(): 能都适配这个Swatch的主体文字的颜色值
  • getTitleTextColor(): 能都适配这个Swatch的标题文字的颜色值

所以我们通过getBodyTextColor()getTitleTextColor()可以很容易得到在这个颜色上可以很好现实的标题和主体文本颜色。所以上面的测试代码完整如下:

var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.a)
var builder = Palette.from(bitmap)
var palette = builder.generate()

color0.setBackgroundColor(palette.getDominantColor(Color.WHITE))
color0.setTextColor(palette.dominantSwatch?.bodyTextColor ?: Color.WHITE)

color1.setBackgroundColor(palette.getMutedColor(Color.WHITE))
color1.setTextColor(palette.mutedSwatch?.bodyTextColor ?: Color.WHITE)

color2.setBackgroundColor(palette.getDarkMutedColor(Color.WHITE))
color2.setTextColor(palette.darkMutedSwatch?.bodyTextColor ?: Color.WHITE)

color3.setBackgroundColor(palette.getLightMutedColor(Color.WHITE))
color3.setTextColor(palette.lightMutedSwatch?.bodyTextColor ?: Color.WHITE)

color4.setBackgroundColor(palette.getVibrantColor(Color.WHITE))
color4.setTextColor(palette.vibrantSwatch?.bodyTextColor ?: Color.WHITE)

color5.setBackgroundColor(palette.getDarkVibrantColor(Color.WHITE))
color5.setTextColor(palette.darkVibrantSwatch?.bodyTextColor ?: Color.WHITE)

color6.setBackgroundColor(palette.getLightVibrantColor(Color.WHITE))
color6.setTextColor(palette.lightVibrantSwatch?.bodyTextColor ?: Color.WHITE)

这样每个颜色上的文字都可以清晰的显示。

那么这个标题和主体文本颜色有什么差别,他们又是如何的到的?我们来看看源码:

/**
 * Returns an appropriate color to use for any 'title' text which is displayed over this
 * {@link Swatch}'s color. This color is guaranteed to have sufficient contrast.
 */
@ColorInt
public int getTitleTextColor() {
    ensureTextColorsGenerated();
    return mTitleTextColor;
}

/**
 * Returns an appropriate color to use for any 'body' text which is displayed over this
 * {@link Swatch}'s color. This color is guaranteed to have sufficient contrast.
 */
@ColorInt
public int getBodyTextColor() {
    ensureTextColorsGenerated();
    return mBodyTextColor;
}

可以看到都会先执行ensureTextColorsGenerated(),它的源码如下:

private void ensureTextColorsGenerated() {
    if (!mGeneratedTextColors) {
        // First check white, as most colors will be dark
        final int lightBodyAlpha = ColorUtils.calculateMinimumAlpha(
                Color.WHITE, mRgb, MIN_CONTRAST_BODY_TEXT);
        final int lightTitleAlpha = ColorUtils.calculateMinimumAlpha(
                Color.WHITE, mRgb, MIN_CONTRAST_TITLE_TEXT);

        if (lightBodyAlpha != -1 && lightTitleAlpha != -1) {
            // If we found valid light values, use them and return
            mBodyTextColor = ColorUtils.setAlphaComponent(Color.WHITE, lightBodyAlpha);
            mTitleTextColor = ColorUtils.setAlphaComponent(Color.WHITE, lightTitleAlpha);
            mGeneratedTextColors = true;
            return;
        }

        final int darkBodyAlpha = ColorUtils.calculateMinimumAlpha(
                Color.BLACK, mRgb, MIN_CONTRAST_BODY_TEXT);
        final int darkTitleAlpha = ColorUtils.calculateMinimumAlpha(
                Color.BLACK, mRgb, MIN_CONTRAST_TITLE_TEXT);

        if (darkBodyAlpha != -1 && darkTitleAlpha != -1) {
            // If we found valid dark values, use them and return
            mBodyTextColor = ColorUtils.setAlphaComponent(Color.BLACK, darkBodyAlpha);
            mTitleTextColor = ColorUtils.setAlphaComponent(Color.BLACK, darkTitleAlpha);
            mGeneratedTextColors = true;
            return;
        }

        // If we reach here then we can not find title and body values which use the same
        // lightness, we need to use mismatched values
        mBodyTextColor = lightBodyAlpha != -1
                ? ColorUtils.setAlphaComponent(Color.WHITE, lightBodyAlpha)
                : ColorUtils.setAlphaComponent(Color.BLACK, darkBodyAlpha);
        mTitleTextColor = lightTitleAlpha != -1
                ? ColorUtils.setAlphaComponent(Color.WHITE, lightTitleAlpha)
                : ColorUtils.setAlphaComponent(Color.BLACK, darkTitleAlpha);
        mGeneratedTextColors = true;
    }
}

通过代码可以看到,这两种文本颜色实际上要么是白色要么是黑色,只是透明度Alpha不同。

这里面有一个关键函数,即ColorUtils.calculateMinimumAlpha()

public static int calculateMinimumAlpha(@ColorInt int foreground, @ColorInt int background,
        float minContrastRatio) {
    if (Color.alpha(background) != 255) {
        throw new IllegalArgumentException("background can not be translucent: #"
                + Integer.toHexString(background));
    }

    // First lets check that a fully opaque foreground has sufficient contrast
    int testForeground = setAlphaComponent(foreground, 255);
    double testRatio = calculateContrast(testForeground, background);
    if (testRatio < minContrastRatio) {
        // Fully opaque foreground does not have sufficient contrast, return error
        return -1;
    }

    // Binary search to find a value with the minimum value which provides sufficient contrast
    int numIterations = 0;
    int minAlpha = 0;
    int maxAlpha = 255;

    while (numIterations <= MIN_ALPHA_SEARCH_MAX_ITERATIONS &&
            (maxAlpha - minAlpha) > MIN_ALPHA_SEARCH_PRECISION) {
        final int testAlpha = (minAlpha + maxAlpha) / 2;

        testForeground = setAlphaComponent(foreground, testAlpha);
        testRatio = calculateContrast(testForeground, background);

        if (testRatio < minContrastRatio) {
            minAlpha = testAlpha;
        } else {
            maxAlpha = testAlpha;
        }

        numIterations++;
    }

    // Conservatively return the max of the range of possible alphas, which is known to pass.
    return maxAlpha;
}

它根据背景色和前景色计算前景色最合适的Alpha。这期间如果小于minContrastRatio则返回-1,说明这个前景色不合适。而标题和主体文本的差别就是这个minContrastRatio不同而已。

回到ensureTextColorsGenerated代码可以看到,先根据当前色调,计算出白色前景色的Alpha,如果两个Alpha都不是-1,就返回对应颜色;否则计算黑色前景色的Alpha,如果都不是-1,返回对应颜色;否则标题和主体文本一个用白色一个用黑色,返回对应颜色即可。

更多功能

上面我们创建Palette时先通过Palette.from(bitmap)的到了一个Palette.Builder对象,通过这个builder可以实现更多功能,比如:

  • addFilter:增加一个过滤器
  • setRegion:设置图片上的提取区域
  • maximumColorCount:调色板的最大颜色数
    等等

总结

通过上面我们看到,Palette的功能很强大,但是它使用起来非常简单,可以让我们很方便的提取图片中的颜色,并且适配合适的文字颜色。同时注意因为ColorUtils是public的,所以当我们需要文字自动适配颜色的情况时,也可以通过ColorUtils的几个函数自己实现计算动态颜色的方案。

Jetpack提供了很多功能模块,比如用于处理通信的ActivityResult,可以参考【Jetpack】ActivityResult介绍及原理分析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/488286.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

送了老弟一台 Linux 服务器,它又懵了!

大家好&#xff0c;我是鱼皮。 前两天我学编程的老弟小阿巴过生日&#xff0c;我问他想要什么礼物。 本来以为他会要什么游戏机、Q 币卡、鼠标键盘啥的&#xff0c;结果小阿巴说&#xff1a;我想要一台服务器。 鱼皮听了&#xff0c;不禁称赞道&#xff1a;真是个学编程的好苗…

演讲回顾 | 释放Atlassian工具的力量

2023年4月14日&#xff0c;Atlassian中国合作伙伴企业日上海站圆满落幕。作为Atlassian全球白金合作伙伴、云专业伙伴&#xff0c;龙智携客户小米参与了此次活动。 小米集团信息技术部SRE薛世英为大家带来主题为《小米集团Jira实战&#xff1a;如何在高负载状态下保持Jira性能与…

Html技术

软件架构&#xff1a; 架构访问端服务端C/SClientServerB/SBrowserServer Html&#xff1a; Hyper Text Markup Language &#xff08;超文本标记语言&#xff09; 简写&#xff1a;HTML HTML 通过标签来标记要显示的网页中的各个部分。 网页文件本身是一种文本文件&#xff0…

Redis类型操作

目录 一、List&#xff08;列表&#xff09; 1.List模板 2.List基本操作(不区分大小写) 2.1添加命令 2.2移除命令 2.3下标索引 2.4列表长度 2.5移除指定值 2.6List截断 2.7移除列表最后一个元素并将他移到新的列表中 2.8替换操作 2.9插入命令 二、Set(集合) 1.Set定义 2…

日撸 Java 三百行day41

文章目录 说明day41 顺序查找与折半查找1.顺序查找2.折半查找3.代码 说明 闵老师的文章链接&#xff1a; 日撸 Java 三百行&#xff08;总述&#xff09;_minfanphd的博客-CSDN博客 自己也把手敲的代码放在了github上维护&#xff1a;https://github.com/fulisha-ok/sampledat…

微信小程序蓝牙功能开发与问题记录

一、蓝牙支持情况 1. 微信小程序对蓝牙的支持情况 目前普遍使用的蓝牙规格&#xff1a;经典蓝牙和蓝牙低功耗。 经典蓝牙&#xff08;蓝牙基础率/增强数据率&#xff09;&#xff1a;常用在对数据传输带宽有一定要求的大数据量传输场景上&#xff0c;比如需要传输音频数据的…

AI工具和用法汇总—集合的集合

AI 工具和用法汇总 汇集整理 by Staok/瞰百&#xff0c;源于相关资料在我这慢慢越积累越多&#xff0c;到了不得不梳理的程度。 文中有许多内容作者还没有亲自尝试&#xff0c;所以很多内容只是罗列&#xff0c;但信息大源都已给出&#xff0c;授人以渔&#xff0c;欢迎 PR 补…

hadoop3.2.1+hive3.1.2-docker安装

Hadoop 1.拉取镜像 docker pull hadoop_hive:32.运行容器 建立hadoop用的内部网络(此步出错&#xff0c;若与其它网段冲突&#xff0c;可省略) #指定固定ip号段 docker network create --driverbridge --subnet172.17.0.1/16 hadoop建立Master容器&#xff0c;映射端口 10…

滚动加载数据

效果图: 综合使用后,觉得还是以下绑定 div监听滚动条的方式好用,有的可以监听滚轮滚动,但是监听不到鼠标拖动滚动条,下面这种方式两者都可以监测到↓ <template><div class"scrollTest-container" id"scrollTestContainer"><div class&quo…

简单分享微信小程序上的招聘链接怎么做

招聘小程序的主要用户就是企业招聘端和找工作人员的用户端,下面从这两个端来对招聘小程序开发的功能进行介绍。 企业端功能 1、岗位发布:企业根据自身岗位需求,在招聘app上发布招聘岗位及所需技能。 2.简历筛选:根据求职者提交的简历选择合适的简历,并对公开发布的简历进行筛…

105.(cesium篇)cesium指南针

听老人家说:多看美女会长寿 地图之家总目录(订阅之前建议先查看该博客) 文章末尾处提供保证可运行完整代码包,运行如有问题,可“私信”博主。 效果如下所示: 下面献上完整代码,代码重要位置会做相应解释 <html lang="en">

【软考高级】2019年系统分析师综合知识

第 1 题 面向对象分析中&#xff0c;一个事物发生变化会影响另一个事物&#xff0c;两个事物之间属于&#xff08;1&#xff09;。 (1) A .关联关系 B .依赖关系 C .实现关系 D .泛化关系 参考答案&#xff1a;(1)B 试题解析&#xff1a; 本题考查的是 UML 图中类的关系…

业务零中断,数据零丢失|庚顿新一代双活高可用架构实时数据库为流程工业核心业务保驾护航

新一代双活架构高可用架构实时数据库管理系统可实现流程工业数据平台“零中断”、“零丢数”的超高可用性要求&#xff0c;在满足实时性要求的同时&#xff0c;实现断网/掉电时业务不中断、不丢数&#xff0c;突破传统主备架构。 随着生产生活自动化、数字化、信息化水平不断升…

二叉树或者多叉树直径问题

原题链接&#xff1a;543. 二叉树的直径 - 力扣&#xff08;LeetCode&#xff09; 题目描述&#xff1a; 给定一棵二叉树&#xff0c;你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 什么是任意两点路径…

ChatGPT来了不用慌,广告人还有这个神器在手

#ChatGPT能取代广告人吗&#xff0c;#ChatGPT会抢走你的工作吗&#xff1f;#ChatGPT火了&#xff0c;会让营销人失业吗&#xff1f;自ChatGPT爆火以来&#xff0c;各种专业or非专业文章不停给广告人强加焦虑&#xff0c;但工具出现的意义&#xff0c;更多在于提效而非替代&…

BetaFlight统一硬件配置文件研读之timer命令

BetaFlight统一硬件配置文件研读之timer命令 1. 源由2. 代码分析3. 实例分析4. 配置情况4.1 AFn配置查表4.2 timer4.3 timer show4.4 timer pin list 5. 参考资料 统一硬件配置文件的设计是一种非常好的设计模式&#xff0c;可以将硬件和软件的工作进行解耦。 1. 源由 cli命令…

某程序员哀叹:二本计算机,4年开发,年包才40多万。二本真的不如985/211吗?

前段时间&#xff0c;某职场论坛上有人发了一个帖子&#xff0c;发帖人问&#xff1a;为什么大家工资那么高&#xff0c;三五年都六七十万了&#xff1f;我二本计算机专业&#xff0c;四年前端开发&#xff0c;找个年包40万多点就顶头了。 原贴如下&#xff1a; 有网友表示楼主…

【Docker】Docker上篇

文章目录 一、认识Docker1、Docker出现的背景2、Docker的历史3、虚拟机技术与容器技术4、容器比虚拟机快的原因5、对Devops层面的影响 二、Docker的安装的原理1、核心名词2、安装Docker&#xff08;for Linux&#xff09;3、配置阿里云镜像加速4、Run的流程和Docker原理 三、Do…

phoenix使用(一)之全局索引的使用

索引使用 1.1. 全局索引&#xff08;Global Indexing&#xff09; 名词解释&#xff1a; 全局索引&#xff0c;适用于读多写少的业务场景。使用Global indexing在写数据的时候开销很大&#xff0c;因为所有对数据表的更新操作&#xff08;DELETE, UPSERT VALUES and UPSERT SEL…

chatgpt软件 - chatbox

文章目录 打开github 进入chatgpt官方要记得登录&#xff01;&#xff01;点击头像将key命名&#xff1a;安装chatbox下面就可以开始使用啦&#xff01;&#xff01; 打开github https://github.com/Bin-Huang/chatbox 特性&#xff1a; 更自由、更强大的 Prompt 能力数据存储…