Thursday, May 31, 2018

android kotlin - Palette API Example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.cfsuman.kotlintutorials.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Get the bitmap from assets
        val bitmap:Bitmap? = assetsBitmap("flower103.jpg")

        // Display the bitmap in image view
        binding.imageView.setImageBitmap(bitmap)

        // Button click listener
        binding.button.setOnClickListener{

            // If bitmap is not null then do the next task
            bitmap?.apply {
                // Get the palette colors
                val list =this.Colors

                // Get the palette color names
                val names = mutableListOf<String>()
                for (i in list){
                    names.add(i.name)
                }

                // Initializing an ArrayAdapter
                val adapter = ArrayAdapter(
                    applicationContext, // Context
                    android.R.layout.simple_spinner_item, // Layout
                    names // Array
                )

                // Set the drop down view resource
                adapter.setDropDownViewResource(
                    android.R.layout.simple_dropdown_item_1line)

                // Finally, data bind the spinner object with adapter
                binding.spinner.adapter = adapter;

                // Set an on item selected listener for spinner object
                binding.spinner.onItemSelectedListener = object: AdapterView
                .OnItemSelectedListener{
                    override fun onItemSelected(
                        parent:AdapterView<*>, view: View,
                        position: Int, id: Long){
                        val item = list[position]

                        binding.textLayout.setBackgroundColor(item.color)

                        binding.tvTitle.text = item.name

                        if (item.swatch!=null){
                            binding.tvTitle.setTextColor(
                                item.swatch.titleTextColor)
                            binding.tvBody.setTextColor(
                                item.swatch.bodyTextColor)
                        }
                    }

                    override fun onNothingSelected(parent: AdapterView<*>){
                        // Another interface callback
                    }
                }
            }
        }
    }
}
PaletteManager.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import androidx.palette.graphics.Palette
import java.io.IOException
import java.io.InputStream


// Extension property to get palette colors from bitmap
val Bitmap.Colors:MutableList<PaletteColor>
    get() {
        // Initialize a list of palette color
        val list = mutableListOf<PaletteColor>()

        // Generate the palette from bitmap
        val palette = this.palette

        // Dark muted color and swatch
        val darkMutedColor = palette.getDarkMutedColor(Color.RED)
        val darkMutedSwatch = palette.darkMutedSwatch
        list.add(PaletteColor(
            "Dark muted color",darkMutedColor,darkMutedSwatch)
        )

        // Dark vibrant color and swatch
        val darkVibrantColor = palette.getDarkVibrantColor(Color.MAGENTA)
        val darkVibrantSwatch = palette.darkVibrantSwatch
        list.add(PaletteColor(
            "Dark vibrant color",
            darkVibrantColor,darkVibrantSwatch))

        // Dominant color and swatch
        val dominantColor = palette.getDominantColor(Color.BLUE)
        val dominantSwatch = palette.dominantSwatch
        list.add(PaletteColor("Dominant Color",
            dominantColor,dominantSwatch))

        // Light muted color and swatch
        val lightMutedColor = palette.getLightMutedColor(Color.YELLOW)
        val lightMutedSwatch = palette.lightMutedSwatch
        list.add(PaletteColor("Light muted color",
            lightMutedColor,lightMutedSwatch))

        // Light vibrant color and swatch
        val lightVibrantColor = palette.getLightVibrantColor(Color.CYAN)
        val lightVibrantSwatch = palette.lightVibrantSwatch
        list.add(PaletteColor("Light vibrant color",
            lightVibrantColor,lightVibrantSwatch))

        // Muted color and swatch
        val mutedColor = palette.getMutedColor(Color.GRAY)
        val mutedSwatch = palette.mutedSwatch
        list.add(PaletteColor("Muted color",mutedColor,mutedSwatch))
        return list
    }


// Initialize a data class to hold the palette color and swatch
data class PaletteColor(val name:String,
                        val color:Int, val swatch: Palette.Swatch?)


// Extension property to generate palette from bitmap
val Bitmap.palette: Palette
    get() {
        return Palette.from(this).generate()
    }


// Extension method get bitmap from assets
fun Context.assetsBitmap(path:String): Bitmap?{
    val inputStream: InputStream
    var bitmap: Bitmap? = null
    try {
        inputStream = assets.open(path)
        bitmap = BitmapFactory.decodeStream(inputStream)
    }catch (e: IOException){
        // Handle exception here
    }

    return bitmap
}
activity_main.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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp"
    android:background="#F8F8FF">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="175dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Generate Palette"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/textLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:textSize="24sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvBody"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:padding="8dp"
            android:textSize="18sp"
            android:text="Lorem Ipsum is simply dummy text of the
            printing and typesetting industry. Lorem Ipsum has been
            the industry's standard dummy text ever since
            the 1500s, when an unknown printer took a galley
            of type and scrambled it to make a type specimen book.
            It has survived not only five centuries,
            but also the leap into electronic typesetting,
            remaining essentially unchanged."
            app:layout_constraintTop_toBottomOf="@+id/tvTitle"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle [app]

implementation 'androidx.palette:palette:1.0.0'
More android examples