Tuesday, June 30, 2020

android kotlin - Circular bitmap with border

MainActivity.kt

package com.example.jetpack

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


class MainActivity : AppCompatActivity() {

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

        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("transparentTulips.png")

        bitmap?.apply {
            // show original bitmap in first image view
            imageView.setImageBitmap(this)

            // crop circular area from bitmap and add border
            imageView2.setImageBitmap(borderedCircularBitmap(
                borderColor = Color.parseColor("#D1E231"),
                borderWidth = 8
            ))
            textView2.text = "Circular Bitmap (Border #D1E231 8 px)"
        }
    }
}


// extension function to get bitmap from assets
fun Context.assetsToBitmap(fileName:String):Bitmap?{
    return try {
        val stream = assets.open(fileName)
        BitmapFactory.decodeStream(stream)
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}


// extension function to create circular bitmap with border
fun Bitmap.borderedCircularBitmap(
    borderColor:Int = Color.LTGRAY,
    borderWidth:Int = 10
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width, // width in pixels
        height, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    // canvas to draw circular bitmap
    val canvas = Canvas(bitmap)

    // get the maximum radius
    val radius = min(width/2f,height/2f)

    // create a path to draw circular bitmap border
    val borderPath = Path().apply {
        addCircle(
            width/2f,
            height/2f,
            radius,
            Path.Direction.CCW
        )
    }

    // draw border on circular bitmap
    canvas.clipPath(borderPath)
    canvas.drawColor(borderColor)


    // create a path for circular bitmap
    val bitmapPath = Path().apply {
        addCircle(
            width/2f,
            height/2f,
            radius - borderWidth,
            Path.Direction.CCW
        )
    }

    canvas.clipPath(bitmapPath)
    val paint = Paint().apply {
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        isAntiAlias = true
    }

    // clear the circular bitmap drawing area
    // it will keep bitmap transparency
    canvas.drawBitmap(this,0f,0f,paint)

    // now draw the circular bitmap
    canvas.drawBitmap(this,0f,0f,null)


    val diameter = (radius*2).toInt()
    val x = (width - diameter)/2
    val y = (height - diameter)/2

    // return cropped circular bitmap with border
    return Bitmap.createBitmap(
        bitmap, // source bitmap
        x, // x coordinate of the first pixel in source
        y, // y coordinate of the first pixel in source
        diameter, // width
        diameter // height
    )
}
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="#FDF5E6"
    tools:context=".MainActivity">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Original Transparent Bitmap"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

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

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Circular Bitmap With Border"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="@+id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

</androidx.constraintlayout.widget.ConstraintLayout>