Search code examples
androidandroid-studiokotlinimageviewrounded-corners

ImageView with rounded corners in Kotlin


I want to have an ImageView with rounded corners in my Fragment. I've got the following Kotlin code:

val imageView: ImageView = root.findViewById(R.id.profile_view)
val pv = RoundedBitmapDrawableFactory.create(res, src)
pv.setCornerRadius = 0f
imageView.setImageDrawable(pv)

create and res are red underlined by Android Stuido. create says:

None of the following functions can be called with the following arguments supplied: - Bitmap? - InputStream - String

res says:

Expression expected, but a package name found.

I hope somebody can help me to fix that problem.

Regards, Jeremy


Solution

  • Please check this

    package com.alok.myapplication
    
    import android.content.Context
    import android.graphics.drawable.BitmapDrawable
    import android.graphics.drawable.Drawable
    import android.util.AttributeSet
    import android.widget.ImageView
    import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
    
    
    class RoundedImageView : ImageView {
    
    constructor(context: Context) : super(context)
    
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )
    
    override fun setImageDrawable(drawable: Drawable?) {
        super.setImageDrawable(drawable)
        val radius = 0.1f
        val bitmap = (drawable as BitmapDrawable).bitmap
        val resourceId = RoundedBitmapDrawableFactory.create(resources, bitmap)
        resourceId.cornerRadius = bitmap.width * radius
        super.setImageDrawable(resourceId)
    }
    }
    

    and add this imageview in your layout

     <com.alok.myapplication.RoundedImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/item_2"/>
    

    I hope it will resolve your issue