Android Palette 颜色提取

1 从一个需求说起。

界面上面有一个卡片,卡片需要动态设置其背景颜色,而这个颜色值需要从卡片上显示的图片上获取。
这就用到了这个类:
android.support.v7.graphics.Palette

Palette 可以从图像中提取突出颜色。
这个类能提取以下突出的颜色:
Vibrant(充满活力的)
Vibrant dark(充满活力的黑)
Vibrant light(充满活力的亮)
Muted(柔和的)
Muted dark(柔和的黑)
Muted lighr(柔和的亮)

2 如何使用
为了方便测试,在代码中没有给卡片设置背景颜色,而是给文字设置了背景颜色。

获取Palette 实例有两种方式:

同步:

Palette palette = Palette.from(bitmap).generate();

异步:

Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
        //TODO
            }
      });

from方法需要传入一个Bitmap对象,Palette就是从这个Bitmap中提取我们需要的颜色。
目前在项目中用同步的方法就可以。

简单实例代码:

public class MainActivity extends AppCompatActivity {

    private int defaultColor ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        paletteBitmapSync(BitmapFactory.decodeResource(getResources(), R.drawable.bd_1));
        defaultColor = getResources().getColor(R.color.defaultColor);
    }

    private void paletteBitmapSync(Bitmap bitmap) {
        Palette palette = Palette.from(bitmap).generate();
        findViewById(R.id.vibrant).setBackgroundColor(palette.getVibrantColor(defaultColor));
        findViewById(R.id.vibrant_dark).setBackgroundColor(palette.getDarkVibrantColor(defaultColor));
        findViewById(R.id.vibrant_light).setBackgroundColor(palette.getLightVibrantColor(defaultColor));
        findViewById(R.id.muted).setBackgroundColor(palette.getMutedColor(defaultColor));
        findViewById(R.id.muted_dark).setBackgroundColor(palette.getDarkMutedColor(defaultColor));
        findViewById(R.id.muted_light).setBackgroundColor(palette.getLightMutedColor(defaultColor));


    }

    private void paletteBitmapAsync(Bitmap bitmap) {

        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                findViewById(R.id.vibrant).setBackgroundColor(palette.getVibrantColor(defaultColor));
                findViewById(R.id.vibrant_dark).setBackgroundColor(palette.getDarkVibrantColor(defaultColor));
                findViewById(R.id.vibrant_light).setBackgroundColor(palette.getLightVibrantColor(defaultColor));
                findViewById(R.id.muted).setBackgroundColor(palette.getMutedColor(defaultColor));
                findViewById(R.id.muted_dark).setBackgroundColor(palette.getDarkMutedColor(defaultColor));
                findViewById(R.id.muted_light).setBackgroundColor(palette.getLightMutedColor(defaultColor));
            }
        });

    }

}

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值