Thursday, May 31, 2018

kotlin - Android Palette API Example

MainActivity.kt

package com.cfsuman.test

import android.graphics.Bitmap
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

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

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

        // Button click listener
        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
                spinner.adapter = adapter;

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

                        linear_layout.setBackgroundColor(item.color)

                        tv_title.text = item.name

                        if (item.swatch!=null){
                            tv_title.setTextColor(item.swatch.titleTextColor)
                            tv_body.setTextColor(item.swatch.bodyTextColor)
                        }

                    }

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

            }
        }
    }
}
PaletteManager.kt

package com.cfsuman.test

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.support.v7.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"?>
<android.support.constraint.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"
    tools:layout_editor_absoluteY="81dp">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="159dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        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"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/linear_layout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        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/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
            />
        <TextView
            android:id="@+id/tv_body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            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."
            android:padding="8dp"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
APP Graddle [Dependencies]

implementation 'com.android.support:palette-v7:27.1.1'