i'm trying to set cornerRadiuse to image view like code below
but sometime in RecyclerView edges go to black
in one of the pages i have to resize an cornerRadus image
i tried to use bitmap instead of this class but it have terrible performance in 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)
}
}
after search a lot i found a library fix this issue
https://github.com/dipkastel/RoundedImageView
its so simple and very useful