android kotlin - Bitmap crop square

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException
import kotlin.math.min

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView = findViewById<TextView>(R.id.textView)
        val textView2 = findViewById<TextView>(R.id.textView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


        bitmap?.apply {
            // show original bitmap in first image view
            imageView.setImageBitmap(this)
            textView.text = "Source Bitmap ($width * $height)"

            // crop bitmap to square
            toSquare()?.let {
                imageView2.setImageBitmap(it)
                textView2.text = "Square Bitmap (${it.width} " +
                        "* ${it.height})"
            }
        }
    }
}



// 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 crop bitmap to square
fun Bitmap.toSquare():Bitmap?{
    // get the small side of bitmap
    val side = min(width,height)

    // calculate the x and y offset
    val xOffset = (width - side) /2
    val yOffset = (height - side)/2

    // create a square bitmap
    // a square is closed, two dimensional shape with 4 equal sides
    return Bitmap.createBitmap(
        this, // source bitmap
        xOffset, // x coordinate of the first pixel in source
        yOffset, // y coordinate of the first pixel in source
        side, // width
        side // 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Rounded corners bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException
import kotlin.math.min

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView2 = findViewById<TextView>(R.id.textView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // create rounded corners bitmap
            imageView2.setImageBitmap(toRoundedCorners(50F))
            textView2.text = "Rounded Corners Bitmap (Corners 50px)"
        }
    }
}


// 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 rounded corners bitmap
fun Bitmap.toRoundedCorners(
    cornerRadius: Float = 25F
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width, // width in pixels
        height, // height in pixels
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)

    // path to draw rounded corners bitmap
    val path = Path().apply {
        addRoundRect(
            RectF(0f,0f,width.toFloat(),height.toFloat()),
            cornerRadius,
            cornerRadius,
            Path.Direction.CCW
        )
    }
    canvas.clipPath(path)

    // draw the rounded corners bitmap on canvas
    canvas.drawBitmap(this,0f,0f,null)
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Rounded Corners Bitmap"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="@+id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

Android Kotlin: How to create a circular bitmap with a border

Introduction

This Android Kotlin tutorial demonstrates how to create a circular bitmap with a border using a custom extension function. The example covers extracting a bitmap image from the assets folder, transforming it into a circular shape, and adding a border around it. This is particularly useful for displaying profile pictures, icons, or thumbnails in a circular form, which is a common design pattern in modern Android apps.

In this example, the image manipulation is done using the Canvas and Paint classes from Android's graphics library, along with a couple of helper functions. The project also makes use of ConstraintLayout to align and display two ImageViews: one for the original image and the other for the circular, bordered version.

MainActivity Breakdown

The MainActivity class extends the Activity class and sets the content view to activity_main.xml, which contains the layout for the app. The layout includes two ImageView components and one TextView to label each image.

Inside onCreate(), the code first references the ImageView and TextView widgets from the XML layout. It then loads a bitmap image named "flower103.jpg" from the assets folder using the assetsToBitmap() function, which is defined as an extension function for the Context class. If the bitmap is successfully retrieved, it is displayed in the first ImageView in its original form.

The next key step is applying the borderedCircularBitmap() extension function to crop the bitmap into a circular shape and add a border. This processed bitmap is displayed in the second ImageView, and the TextView is updated to describe the transformation that has been applied to the image.

assetsToBitmap() Function

The assetsToBitmap() function is a helper that retrieves a bitmap image from the app's assets folder. It takes the filename as an argument and uses a try-catch block to handle potential IOException errors. If successful, it returns a decoded bitmap using BitmapFactory.decodeStream(). If it encounters an error, it logs the exception and returns null.

This function simplifies loading images stored within the app's resources, providing a clean way to access asset images without having to write repetitive code.

borderedCircularBitmap() Function

The borderedCircularBitmap() function is the core of this example. It converts a square bitmap into a circular one with an optional border. This function operates by creating a new bitmap of the same dimensions as the original. A Canvas is then used to draw the circular shape, and the Path class defines the border and the circular crop region.

To draw the border, the function first creates a circular path corresponding to the radius of the bitmap and uses clipPath() to constrain the drawing to this path. The border is drawn using the drawColor() method, which fills the clipped circular area with the specified border color.

The function then creates another circular path, slightly smaller than the first to account for the border width, and clips the bitmap again to ensure the image is drawn inside this smaller circle. The bitmap is then drawn onto the canvas twice: once to clear the drawing area and once to overlay the actual image, preserving transparency.

Finally, the function crops the newly created circular bitmap to the exact size of the circle and returns the result. This method ensures the final bitmap is centered and has a clean circular border.

Layout Overview

The activity_main.xml file defines the UI layout using a ConstraintLayout for flexible positioning. It includes two ImageView elements for displaying the original and processed bitmaps, along with corresponding TextView labels.

The layout ensures that both images are centered horizontally on the screen and have consistent padding. The second ImageView is placed below the first with adequate spacing to provide a clear distinction between the original and circular bordered images.

Summary

This example demonstrates how to create a circular bitmap with a border in Android using Kotlin. By leveraging extension functions, the code is modular and reusable, making it easier to implement similar functionality in other parts of an app. The Canvas and Path classes from Android's graphics API are used to handle the drawing and clipping operations, while the custom assetsToBitmap() and borderedCircularBitmap() functions simplify the process of loading and transforming images.

The final layout is minimalistic, but it clearly illustrates how to present both the original and modified images on the screen, making it a great starting point for developers looking to implement circular image views in their apps.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException
import kotlin.math.min

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView2 = findViewById<TextView>(R.id.textView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


        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("#F8F8F8"),
                borderWidth = 12
            ))
            textView2.text = "Circular Bitmap (Border #F8F8F8 12 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="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>
More android kotlin tutorials

android kotlin - Bitmap crop circular area

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException
import kotlin.math.min

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // crop circular area from bitmap
            imageView2.setImageBitmap(cropCircularArea())
        }
    }
}



// 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 crop circular area from bitmap
fun Bitmap.cropCircularArea():Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width, // width in pixels
        height, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)

    // create a circular path
    val path = Path()
    val radius = min(width/2f,height/2f)
    path.apply {
        addCircle(
            width/2f,
            height/2f,
            radius,
            Path.Direction.CCW
        )
    }

    // draw circular bitmap on canvas
    canvas.clipPath(path)
    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
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Bitmap add border

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView2 = findViewById<TextView>(R.id.textView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // add border to bitmap
            // and keep bitmap transparency
            imageView2.setImageBitmap(addBorder(
                color = Color.parseColor("#F8F8F8"),
                borderWidth = 20
            ))
            textView2.text = "Bitmap Border 20 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 add border to bitmap
fun Bitmap.addBorder(
    color:Int = Color.DKGRAY,
    borderWidth:Int = 10
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width + borderWidth * 2, // width in pixels
        height + borderWidth * 2, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)

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

    // clear color from bitmap drawing area
    // this is very important for transparent bitmap border
    // this will keep bitmap transparency
    Paint().apply {
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        canvas.drawRect(
            Rect(
                borderWidth, // left
                borderWidth, // top
                bitmap.width - borderWidth, // right
                bitmap.height - borderWidth // bottom
            ),
            this
        )
    }

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

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Bitmap add padding

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView2 = findViewById<TextView>(R.id.textView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // add padding to bitmap
            // and keep bitmap transparency
            imageView2.setImageBitmap(addPadding(
                color = Color.parseColor("#F8F8F8"),
                left = 10,
                top = 20,
                right = 30,
                bottom = 40
            ))
            textView2.text = "Padding (10,20,30,40)"
        }
    }
}



// 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 add padding to bitmap
fun Bitmap.addPadding(
    color:Int = Color.GRAY,
    left:Int = 0,
    top:Int = 0,
    right:Int = 0,
    bottom:Int = 0
):Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width + left + right, // width in pixels
        height + top + bottom, // height in pixels
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)

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

    // clear color from bitmap drawing area
    // this is very important for transparent bitmap borders
    // this will keep bitmap transparency
    Paint().apply {
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        canvas.drawRect(
            Rect(left,top,bitmap.width - right,
                bitmap.height - bottom),
            this
        )
    }

    // finally, draw bitmap on canvas
    Paint().apply {
        canvas.drawBitmap(
            this@addPadding, // bitmap
            0f + left, // left
            0f + top, // top
            this // paint
        )
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Bitmap draw shadow

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // draw shadow on bitmap
            // show bitmap with shadow in second image view
            imageView2.setImageBitmap(drawShadow())
        }
    }
}



// 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 draw shadow on bitmap
fun Bitmap.drawShadow():Bitmap?{
    val bitmap = Bitmap.createBitmap(
        width + 10,
        height + 10,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)

    val paint = Paint().apply {
        isAntiAlias = true

        // draw shadow right and bottom side of bitmap
        /*
            This draws a shadow layer below the main layer,
            with the specified offset and color, and blur radius.
        */
        setShadowLayer(
            10f, // radius
            6f, // dx
            6f, // dy
            Color.BLACK // color
        )
    }

    canvas.drawBitmap(this,0f,0f,paint)
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Draw rectangle on bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower2.jpg")


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

            // draw rectangle on bitmap
            // show bitmap with rectangle in second image view
            imageView2.setImageBitmap(drawRectangle())
        }
    }
}



// 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 draw rectangle on bitmap
fun Bitmap.drawRectangle():Bitmap?{
    val bitmap = copy(config,true)
    val canvas = Canvas(bitmap)

    Paint().apply {
        color = Color.parseColor("#A1CAF1")
        isAntiAlias = true

        // draw rectangle on canvas
        canvas.drawRect(
            20f, // left side of the rectangle to be drawn
            20f, // top side
            width/3 - 20f, // right side
            height - 20f, // bottom side
            this
        )
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Draw line on bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower2.jpg")


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

            // draw line on bitmap
            // show bitmap with line in second image view
            imageView2.setImageBitmap(drawLine())
        }
    }
}



// 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 draw line on bitmap
fun Bitmap.drawLine():Bitmap?{
    val bitmap = copy(config,true)
    val canvas = Canvas(bitmap)

    Paint().apply {
        color = Color.parseColor("#007FFF")
        strokeWidth = 10f

        // draw line on canvas
        canvas.drawLine(
            10f, // The x-coordinate of the start point of the line
            10f, // The y-coordinate of the start point of the line
            width - 10f, // stopX
            height - 10f, // stopY
            this // paint
        )
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Draw circle on bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower2.jpg")


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

            // draw circle on bitmap
            // show bitmap with circle in second image view
            imageView2.setImageBitmap(drawCircle())
        }
    }
}



// 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 draw circle on bitmap
fun Bitmap.drawCircle(
    radius:Float = 100f,
    color:Int = Color.parseColor("#A2A2D0")
):Bitmap?{
    val bitmap = copy(config,true)
    val canvas = Canvas(bitmap)

    Paint().apply {
        this.color = color

        // draw circle on left bottom of bitmap
        canvas.drawCircle(
            // x-coordinate of the center of the circle to be drawn
            radius + 10f,
            // y-coordinate of the center of the circle to be drawn
            height - radius - 10f,
            radius, // radius of the circle to be drawn
            this // paint
        )
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Draw text on bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("rose.jpg")


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

            // draw text on bitmap
            // show bitmap with text in second image view
            imageView2.setImageBitmap(drawText())
        }
    }
}



// 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 draw text on bitmap
fun Bitmap.drawText(
    text:String = "Cute Rose",
    textSize:Float = 55f,
    color:Int = Color.YELLOW
):Bitmap?{
    val bitmap = copy(config,true)
    val canvas = Canvas(bitmap)

    Paint().apply {
        flags = Paint.ANTI_ALIAS_FLAG
        this.color = color
        this.textSize = textSize
        typeface = Typeface.SERIF
        setShadowLayer(1f,0f,1f,Color.WHITE)
        canvas.drawText(text,20f,height - 20f,this)
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        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_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Bitmap color matrix set scale

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException


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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val seekBarRed = findViewById<SeekBar>(R.id.seekBarRed)
        val seekBarGreen = findViewById<SeekBar>(R.id.seekBarGreen)
        val seekBarBlue = findViewById<SeekBar>(R.id.seekBarBlue)
        val seekBarAlpha = findViewById<SeekBar>(R.id.seekBarAlpha)
        val tvIntensity = findViewById<TextView>(R.id.tvIntensity)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower103.jpg")


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

            // show initial bitmap on second image view
            imageView2.setImageBitmap(scaleChannels())


            seekBarRed.setOnSeekBarChangeListener(object:SeekBar
            .OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    val red = progress.toFloat()/10
                    val green = seekBarGreen.progress.toFloat()/10
                    val blue = seekBarBlue.progress.toFloat()/10
                    val alpha = seekBarAlpha.progress.toFloat()/10

                    imageView2.setImageBitmap(
                        scaleChannels(red,green,blue,alpha))
                    tvIntensity.text = "(Red $red : Green $green : "
                    tvIntensity.append("Blue $blue : Alpha $alpha)")
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                }
            })


            seekBarGreen.setOnSeekBarChangeListener(object:SeekBar
            .OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    val red = seekBarRed.progress.toFloat()/10
                    val green = progress.toFloat()/10
                    val blue = seekBarBlue.progress.toFloat()/10
                    val alpha = seekBarAlpha.progress.toFloat()/10

                    imageView2.setImageBitmap(
                        scaleChannels(red,green,blue,alpha))
                    tvIntensity.text = "(Red $red : Green $green : "
                    tvIntensity.append("Blue $blue : Alpha $alpha)")
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                }
            })


            seekBarBlue.setOnSeekBarChangeListener(object:SeekBar
            .OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    val red = seekBarRed.progress.toFloat()/10
                    val green = seekBarGreen.progress.toFloat()/10
                    val blue = progress.toFloat()/10
                    val alpha = seekBarAlpha.progress.toFloat()/10

                    imageView2.setImageBitmap(
                        scaleChannels(red,green,blue,alpha))
                    tvIntensity.text = "(Red $red : Green $green : "
                    tvIntensity.append("Blue $blue : Alpha $alpha)")
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                }
            })


            seekBarAlpha.setOnSeekBarChangeListener(object:SeekBar
            .OnSeekBarChangeListener{
                override fun onProgressChanged(
                    seekBar: SeekBar?,
                    progress: Int,
                    fromUser: Boolean
                ) {
                    val red = seekBarRed.progress.toFloat()/10
                    val green = seekBarGreen.progress.toFloat()/10
                    val blue = seekBarBlue.progress.toFloat()/10
                    val alpha = progress.toFloat()/10

                    imageView2.setImageBitmap(
                        scaleChannels(red,green,blue,alpha))
                    tvIntensity.text = "(Red $red : Green $green : "
                    tvIntensity.append("Blue $blue : Alpha $alpha)")
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                }

                override fun onStopTrackingTouch(seekBar: SeekBar?) {
                }
            })
        }
    }
}


// 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 scale bitmap color channels
fun Bitmap.scaleChannels(
    red:Float = 1F,
    green:Float = 1F,
    blue:Float = 1F,
    alpha:Float = 1F
):Bitmap?{
    val bitmap = copy(config,true)
    val paint = Paint()

    val matrix = ColorMatrix().apply {
        setScale(red,green,blue,alpha)
    }

    val filter  = ColorMatrixColorFilter(matrix)
    paint.colorFilter = filter

    Canvas(bitmap).drawBitmap(this,0f,0f,paint)
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

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

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="210dp"
        android:layout_marginTop="16dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/imageView2">

        <TextView
            android:id="@+id/tvIntensity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:gravity="center_horizontal"
            android:text="Channels Intensity"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <SeekBar
            android:id="@+id/seekBarRed"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:max="20"
            android:progress="10"
            android:progressTint="#ff0000"
            android:progressBackgroundTint="#ff0000"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvIntensity" />

        <SeekBar
            android:id="@+id/seekBarGreen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:max="20"
            android:progress="10"
            android:progressTint="#00ff00"
            android:progressBackgroundTint="#00ff00"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/seekBarRed" />

        <SeekBar
            android:id="@+id/seekBarBlue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:max="20"
            android:progress="10"
            android:progressTint="#0000ff"
            android:progressBackgroundTint="#0000ff"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/seekBarGreen" />

        <SeekBar
            android:id="@+id/seekBarAlpha"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:max="20"
            android:progress="10"
            android:progressTint="#000000"
            android:progressBackgroundTint="#000000"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/seekBarBlue" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - Bitmap remove transparency

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.renderscript.*
import android.widget.*
import java.io.IOException


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

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView2 = findViewById<TextView>(R.id.textView2)
        val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)


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

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

            // show bitmap without transparent pixels on second image view
            imageView2.setImageBitmap(removeTransparency())

            // remove bitmap transparency by specified solid color
            radioGroup.setOnCheckedChangeListener { radioGroup, i ->
                var color = Color.WHITE
                var name = "White"
                when(i){
                    R.id.radioWhite->{color = Color.WHITE; name = "White"}
                    R.id.radioGray->{color = Color.GRAY; name = "Gray"}
                    R.id.radioYellow->{color = Color.YELLOW; name = "Yellow"}
                }

                textView2.text = "Replace By $name"
                imageView2.setImageBitmap(removeTransparency(color))
            }
        }
    }
}


// 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 remove bitmap transparency
fun Bitmap.removeTransparency(backgroundColor:Int = Color.WHITE):Bitmap?{
    val bitmap = copy(config,true)
    var alpha:Int
    var red:Int
    var green:Int
    var blue:Int
    var pixel:Int

    // scan through all pixels
    for (x in 0 until width){
        for (y in 0 until height){
            pixel = getPixel(x,y)
            alpha = Color.alpha(pixel)
            red = Color.red(pixel)
            green = Color.green(pixel)
            blue = Color.blue(pixel)

            if (alpha == 0){
                // if pixel is full transparent then
                // replace it by solid background color
                bitmap.setPixel(x,y,backgroundColor)
            }else{
                // if pixel is partially transparent then
                // set pixel full opaque
                val color = Color.argb(
                    255,
                    red,
                    green,
                    blue
                )
                bitmap.setPixel(x,y,color)
            }
        }
    }

    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="225dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="225dp"
        android:layout_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/imageView2">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Replace By White"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView2">

            <RadioButton
                android:id="@+id/radioWhite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="White" />

            <RadioButton
                android:id="@+id/radioGray"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Gray" />

            <RadioButton
                android:id="@+id/radioYellow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Yellow" />

        </RadioGroup>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials