ImageView with rounded corners in Kotlin

旧街凉风 提交于 2020-04-18 05:36:07

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/58033444/imageview-with-rounded-corners-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!