简介
Palette是Android的调色板,能够从图像中提取图片的颜色。使用Palette提取的颜色融入到UI设计当中,使app更加美观,增加用户体验。如:根据滑动的页面的整体风格,通过Palette获取得到的颜色值,设置不同的actionbar底色,使整体页面更加精美。
添加Palette依赖
Android的API中目前还没有加入Palette,需要手动添加Palette依赖,在Project Structure中添加。
使用
添加了依赖之后,项目中就可以使用Palette了,那么接下来就直接上代码吧。
简单布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.main.palette.PaletteActivity">
<TextView
android:id="@+id/palette_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="20dp"
android:text="调色板"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:src="@drawable/aa"/>
</LinearLayout>
复制代码
在Activity中使用:
public class PaletteActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_palette);
mTextView = (TextView)this.findViewById(R.id.palette_text);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.aa);
// Synchronous同步
//Palette p = Palette.from(bitmap).generate();
// Asynchronous异步
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette p) {
// Use generated instance
//暗、柔和的颜色
int darkMutedColor = p.getDarkMutedColor(Color.BLUE);//如果分析不出来,则返回默认颜色
//暗、柔和
int lightMutedColor = p.getLightMutedColor(Color.BLUE);
//暗、鲜艳
int darkVibrantColor = p.getDarkVibrantColor(Color.BLUE);
//亮、鲜艳
int lightVibrantColor = p.getLightVibrantColor(Color.BLUE);
//柔和
int mutedColor = p.getMutedColor(Color.BLUE);
//柔和
int vibrantColor = p.getVibrantColor(Color.BLUE);
mTextView.setBackgroundColor(getTranslucentColor(0.5f,darkMutedColor));
}
});
}
/**
* 返回argb的格式
* @param percent
* @param rgb
* @return
*/
protected int getTranslucentColor(float percent, int rgb) {
int blue = Color.blue(rgb);
int green = Color.green(rgb);
int red = Color.red(rgb);
int alpha = Color.alpha(rgb);
alpha = Math.round(alpha*percent);
return Color.argb(alpha, red, green, blue);
}
复制代码
首先要获取图片的bitmap,然后Palette会从bitmap中分析图片的色彩,并且Palette会提供方法给开发者获取图片的色彩。
根据提供的bitmap,有两种方式可以获取得到Palette对象:
1)同步:Palette.from(bitmap).generate();
2)异步:Palette.from(bitmap).generate(new Palette.PaletteAsyncListener())
一般的在主线程执行比较耗时的任务会出现ANR,所有如果是比较耗时的操作还是选择使用异步来获取比较好。
得到Palette对象就可以根据方法获取得到自己需要的颜色值,如在以上代码中列出来的方法可以获取得到不同的颜色值,开发者根据自己的需要做出精美的UI。关于Palette的更多方法,可以查看其API。
注意
Palette对象获取得到的颜色值有可能为null,所以最好做一个判空的操作,防止程序crash。
效果图
这里设置的title的背景颜色是:通过Palette获取得到bitmap的暗、柔和的颜色。