Android中使用Palette让你的页面UI优雅起来

1. 什么是Palette

Palette 翻译过来是调色板的意思,在android开发中,它的作用是自动分析一张图片中的色调,并且提取出合适的颜色,来帮我们进行动态配色
所谓的动态配色,是说根据页面中不同图片的色调,自动为其他部分的View设置背景色,以达到视觉上的协调,美观。

比如,根据页面中图片的色调,改变ToolBar的背景色,状态栏的颜色;根据卡片图片的色调,改变图片上文字的背景色等场景。

2. 引入Palette

在 moudle级别的 build.gradle 中添加 palette 的依赖

// java 工程
implementation 'androidx.palette:palette:1.0.0'

// kotlin 工程
implementation 'androidx.palette:palette-ktx:1.0.0'

3. 使用 Palette

首先是获取 palette 对象。根据Bitmap,我们可以

3.1 同步方式

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.test1)
val paletteBuilder = Palette.from(bitmap)
val palette = paletteBuilder.generate()

3.2 异步方式

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.test1)
val paletteBuilder = Palette.from(bitmap)
paletteBuilder.generate(object : PaletteAsyncListener {
    override fun onGenerated(palette: Palette?) {
        // 得到了 palette
    }
})
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
// 同步
Palette.Builder builder = Palette.from(bitmap);
Palette palette=builder.generate();
// 异步
builder.generate(bitmap, new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
    }
}

3.3 获取色调值

获取了 Palette 对象后,就可以调用它的各种方法,获取各种我们需要的色调值了。

Palette.from(it).generate(object : PaletteAsyncListener{
     override fun onGenerated(palette: Palette?) {
          palette ?: return
          // 获取到柔和的深色的颜色, Color.GREEN是获取不到时的默认颜色
          val darkMutedColor = palette.getDarkMutedColor(Color.GREEN)
          // 获取到柔和的明亮的颜色
          val lightMutedColor = palette.getLightMutedColor(Color.GREEN)
          // 获取到活跃的深色的颜色
          val darkVibrantColor = palette.getDarkVibrantColor(Color.GREEN)
          // 获取到活跃的明亮的颜色
          val lightVibrantColor = palette.getLightVibrantColor(Color.GREEN)
          // 获取图片中一个最柔和的颜色
          val mutedColor = palette.getMutedColor(Color.GREEN)
          // 获取图片中最活跃的颜色,也可以说整个图片出现最多的颜色
          val vibrantColor = palette.getVibrantColor(Color.GREEN)

          // 获取某种特性颜色的样品
          val lightVibrantSwatch = palette.vibrantSwatch
          // 谷歌推荐的:图片的整体的颜色rgb的混合值---主色调
          val rgb = lightVibrantSwatch?.rgb
          // 谷歌推荐:图片中间的文字颜色
          val bodyTextColor = lightVibrantSwatch?.bodyTextColor
          // 谷歌推荐:作为标题的颜色(有一定的和图片的对比度的颜色值)
          val titleTextColor = lightVibrantSwatch?.titleTextColor
          // 颜色向量
          val hsl = lightVibrantSwatch?.hsl
          // 分析该颜色在图片中所占的像素多少值
          val population = lightVibrantSwatch?.population
      }
  })

4. 举例

用 palette 做一个优雅的卡片列表。

4.1 布局文件 activity_palette_list.xml ⬇️

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".palette.PaletteListActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcv_palette"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4.2 Activity:PaletteListActivity⬇️

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.example.mytest.R
import com.example.mytest.databinding.ActivityPaletteListBinding

class PaletteListActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityPaletteListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val dataList = mutableListOf<PaletteBean>(
            PaletteBean(R.drawable.test1, "标题1"),
            PaletteBean(R.drawable.test2, "hello2"),
            PaletteBean(R.drawable.test3, "hello3"),
            PaletteBean(R.drawable.test4, "hello4"),
            PaletteBean(R.drawable.test1, "标题1"),
            PaletteBean(R.drawable.test2, "hello2"),
            PaletteBean(R.drawable.test3, "hello3"),
            PaletteBean(R.drawable.test4, "hello4"),
            PaletteBean(R.drawable.test1, "标题1"),
            PaletteBean(R.drawable.test2, "hello2"),
            PaletteBean(R.drawable.test3, "hello3"),
            PaletteBean(R.drawable.test4, "hello4"),
        )
        binding.rcvPalette.apply {
            adapter = PaletteListAdapter(dataList)
            layoutManager = GridLayoutManager(this@PaletteListActivity, 2)
        }
    }
}

4.3 列表Adapter:PaletteListAdapter ⬇️

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.drawable.toBitmapOrNull
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.RecyclerView
import com.example.mytest.databinding.ListItemPaletteBinding
import kotlin.math.roundToInt

class PaletteListAdapter(private val dataList: MutableList<PaletteBean> = mutableListOf()) :
    RecyclerView.Adapter<PaletteListAdapter.MyViewHolder>() {

    fun update(lDataList: List<PaletteBean>) {
        dataList.clear()
        dataList.addAll(lDataList)
        notifyDataSetChanged()
    }

    class MyViewHolder(val binding: ListItemPaletteBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(data: PaletteBean?) {
            data ?: return
            binding.ivCover.setImageResource(data.imgId)
            binding.tvContent.text = data.title

            val bitmap = binding.ivCover.drawable.toBitmapOrNull()
            bitmap?.let {
                Palette.from(it).generate { palette ->
                    val titleColor = palette?.vibrantSwatch?.titleTextColor
                    val bg = getTranslucentColor(0.5f, palette?.vibrantSwatch?.rgb!!)
                    binding.tvContent.setTextColor(titleColor!!)
                    binding.tvContent.setBackgroundColor(bg)
                }
            }
        }

        /**
         * 获取指定透明度的颜色值
         */
        private fun getTranslucentColor(percent: Float, rgb: Int): Int {
            val blue = Color.blue(rgb)
            val green = Color.green(rgb)
            val red = Color.red(rgb)
            var alpha = Color.alpha(rgb)
            alpha = (alpha * percent).roundToInt()
            return Color.argb(alpha, red, green, blue)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

        val binding =
            ListItemPaletteBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return dataList?.size ?: 0
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(dataList?.get(position))
    }
}

4.4 列表item布局:list_item_palette.xml ⬇️

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    app:cardCornerRadius="4dp"
    app:cardElevation="1dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="150dp">

        <ImageView
            android:id="@+id/iv_cover"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/test1"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="你好啊"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

4.5 效果

请添加图片描述

怎么样?这样卡片底部的蒙层就合图片的主色调一致,文字颜色也是相对和谐的,整体看起来就优雅多了吧。

如果这篇文章对你有用的话,欢迎支持哦~感谢!

  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子林Android

感谢老板,老板大气!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值