recyclerview 中的黑色圆边

black Rounded edge in recyclerview

我正在尝试将 cornerRadiuse 设置为图像视图,如下面的代码

但有时在 RecyclerView 中边缘会变黑

在其中一个页面中,我必须调整 cornerRadus 图像的大小

我尝试使用位图而不是这个 class 但是它在 recyclerview 中的表现很糟糕

class CImageView : AppCompatImageView {

private var mMaskPath: Path = Path()
private val mMaskPaint = Paint(Paint.ANTI_ALIAS_FLAG)
var mCornerRadius = 0f
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
    init(attributeSet)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
    init( attrs)
}
private fun init(set: AttributeSet?) {
    if(isInEditMode) {
        return
    }
    if (set == null) {
        return
    }
    ViewCompat.setLayerType(this, View.LAYER_TYPE_SOFTWARE, null)
    mMaskPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    mMaskPaint.color = resources.getColor(R.color.accent_material_dark)

    val ta = getContext().obtainStyledAttributes(set, R.styleable.CImageView)
    mCornerRadius = ta.getDimension(R.styleable.CImageView_cornerRadiuses, 0f)
    ta.recycle()
    invalidate()
}
override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) {
    super.onSizeChanged(w, h, oldW, oldH)

    if (w != oldW || h != oldH) {
        generateMaskPath(w, h)
        try {
            val s = w.toFloat() / oldW * mCornerRadius
            if (s < 100)
                mCornerRadius = s
        } catch (e: Exception) {
        }
    }
    invalidate()
}

private fun generateMaskPath(w: Int, h: Int) {
    try{
    mMaskPath = Path()
    mMaskPath.addRoundRect(RectF(0f, 0f, w.toFloat(), h.toFloat()), mCornerRadius, mCornerRadius, Path.Direction.CW)
    mMaskPath.fillType = Path.FillType.INVERSE_WINDING
    }catch (e:Exception){
        //whene h = 0 => image not load on screen
    }
}
override fun onDraw(canvas: Canvas) {
    if(isInEditMode){
        super.onDraw(canvas)
        return
    }
    if (canvas.isOpaque) {
        canvas.saveLayerAlpha(0f, 0f, width.toFloat(), height.toFloat(), 255, 0)
    }
    super.onDraw(canvas)
    canvas.drawPath(mMaskPath, mMaskPaint)
}
}

经过大量搜索后,我找到了一个库来解决这个问题
https://github.com/dipkastel/RoundedImageView
它非常简单而且非常有用

您也可以使用 Glide 加载图像并添加 rounded corners transformation

Glide.with(imgView)
.load("http://my_image.jpeg")
.apply(RequestOptions().transform(RoundedCorners(12))) // This is the corner radius in pixels
.into(imgView)