Kotlin 中带圆角的 ImageView

ImageView with rounded corners in Kotlin

我想在我的 Fragment 中有一个带圆角的 ImageView。 我有以下 Kotlin 代码:

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

create 和 res 由 Android Stuido 加红色下划线。 创建说:

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

res 说:

Expression expected, but a package name found.

我希望有人能帮我解决这个问题。

此致,杰里米

请检查这个

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)
}
}

并将此图像视图添加到您的布局中

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

希望能解决您的问题

您可以使用 Glide 库轻松完成。

Glide.with(imageView.context)
            .load(pictureUri)
            .apply(
                RequestOptions()
                    .transform(RoundedCorners(25))
            .into(imageView)