How to create ImageView with rounded corners in Android Kotlin

In this android kotlin source code example, we are going to create ImageView with rounded corners in Android Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to create ImageView with rounded corners in Android Kotlin

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"
    tools:context=".imageView.ImageViewActivity15">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

import android.graphics.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import com.bluapp.kotlinview.R
import android.graphics.drawable.BitmapDrawable



class ImageViewActivity15 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_view15)
        val imageView = findViewById<ImageView>(R.id.imageView) as ImageView
        val bitmap = (resources.getDrawable(R.drawable.profilepic) as BitmapDrawable).bitmap
        val bitmapRounded = Bitmap.createBitmap(bitmap.width, bitmap.height, bitmap.config)
        val canvas = Canvas(bitmapRounded)
        val paint = Paint()
        paint.setAntiAlias(true)
        paint.setShader(BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP))
        canvas.drawRoundRect(RectF(0.0f, 0.0f, bitmap.width.toFloat(), bitmap.height.toFloat()), 30.0f, 30.0f, paint)
        imageView.setImageBitmap(bitmapRounded)
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment