Friday, August 21, 2020

android kotlin - ImageView border shadow

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException


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

        // get context
        val context = this

        // image view image border color
        val borderColor:Int = Color.parseColor("#3B2F2F")

        // get bitmap from assets and show it on image view
        val bitmap: Bitmap? = assetsToBitmap("flowers2.jpg")

        // set border and shadow on second image view
        bitmap?.addBorder(borderColor = borderColor)?.addShadow(
            shadowRadius = 10.dpToPixels(context)
        )?.apply {
            imageView.setImageBitmap(this)
        }

        // set only border to second image view
        bitmap?.addBorder(borderColor = borderColor)?.apply {
            imageView2.setImageBitmap(this)
        }
    }
}


// extension function to add border to bitmap
fun Bitmap.addBorder(
    borderColor:Int = Color.DKGRAY,
    borderWidth:Int = 30,
    paddingColor:Int = Color.WHITE,
    paddingWidth:Int = 200
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width + borderWidth * 2 + paddingWidth * 2, // width in pixels
        height + borderWidth * 2 + paddingWidth * 2, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)

    // draw solid color on full canvas area
    canvas.drawColor(borderColor)

    // draw color on padding area
    Paint().apply {
        color = paddingColor
        canvas.drawRect(
            Rect(
                borderWidth, // left
                borderWidth, // top
                bitmap.width - borderWidth, // right
                bitmap.height - borderWidth // bottom
            ),
            this
        )
    }

    // clear bitmap area
    Paint().apply {
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        canvas.drawRect(
            Rect(
                borderWidth + paddingWidth, // left
                borderWidth + paddingWidth, // top
                bitmap.width - borderWidth - paddingWidth, // right
                bitmap.height - borderWidth - paddingWidth// bottom
            ),
            this
        )
    }

    // finally, draw bitmap on canvas
    Paint().apply {
        canvas.drawBitmap(
            this@addBorder, // bitmap
            paddingWidth.toFloat() + borderWidth, // left
            paddingWidth.toFloat() + borderWidth, // top
            this // paint
        )
    }

    return bitmap
}


// extension function to add shadow around bitmap
fun Bitmap.addShadow(
    shadowRadius:Int = 20,
    paddingColor:Int = Color.TRANSPARENT,
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width + shadowRadius, // width in pixels
        height  + shadowRadius, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)

    // draw solid color on full canvas area
    canvas.drawColor(paddingColor)

    // finally, draw bitmap on canvas
    Paint().apply {
        setShadowLayer(
            shadowRadius.toFloat(), // radius
            shadowRadius / 2F, // dx
            shadowRadius / 2F, // dy
            Color.BLACK // color
        )

        canvas.drawBitmap(
            this@addShadow, // bitmap
            0F, // left
            0F, // top
            this // paint
        )
    }

    return bitmap
}


// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics
).toInt()


// extension function to get bitmap from assets
fun Context.assetsToBitmap(fileName: String): Bitmap?{
    return try {
        with(assets.open(fileName)){
            BitmapFactory.decodeStream(this)
        }
    } catch (e: IOException) { null }
}
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/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="Border Shadow"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

</androidx.constraintlayout.widget.ConstraintLayout>