【问题标题】:black Rounded edge in recyclerview回收站视图中的黑色圆边
【发布时间】:2019-08-26 13:54:45
【问题描述】:

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

但有时在 RecyclerView 边缘会变黑

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

我尝试使用位图代替此类,但它在 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)
}
}

【问题讨论】:

    标签: android imageview android-custom-view cornerradius


    【解决方案1】:

    您也可以使用 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)
    

    【讨论】:

    • 嗨,欢迎来到 StackOverflow,您能否将一些代码 sn-ps 或示例也包含在答案中,因为仅提供链接风险太大,该页面可能稍后不可用:)
    【解决方案2】:

    经过大量搜索后,我找到了一个修复此问题的库
    https://github.com/dipkastel/RoundedImageView
    它是如此简单,非常有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2016-09-22
      • 2016-02-02
      • 1970-01-01
      相关资源
      最近更新 更多