Thursday, August 20, 2020

android kotlin - ImageView add border programmatically

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
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 bitmap from assets
        val bitmap: Bitmap? = assetsToBitmap("flower3.jpg")

        // set image view image from assets
        bitmap?.apply {
            imageView.setImageBitmap(this)
        }

        // create a new shape drawable and use it for image view border
        imageView.background = imageViewBorder(
            borderColor = Color.parseColor("#483D8B"),
            borderWidthInDp = 10
        )
    }
}


// extension function to make a border for image view
fun Context.imageViewBorder(
    borderColor:Int = Color.BLACK,
    borderWidthInDp: Int = 5
): ShapeDrawable{
    // convert dp to equivalent pixels value for border
    val borderWidthInPixels = borderWidthInDp.dpToPixels(this)

    val shapeDrawable = ShapeDrawable(RectShape())

    // specify the border properties
    shapeDrawable.paint.apply {
        color = borderColor
        style = Paint.Style.STROKE
        strokeWidth = borderWidthInPixels
        isAntiAlias = true
        flags = Paint.ANTI_ALIAS_FLAG
    }

    // set padding for drawable
    val padding = (borderWidthInPixels * 2).toInt()
    shapeDrawable.setPadding(padding,padding,padding,padding)

    // return image view border as shape drawable
    return shapeDrawable
}


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


// 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="#F0FFFF"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="300dp"
        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" />

</androidx.constraintlayout.widget.ConstraintLayout>