【发布时间】: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