圆角View(ImageView,Gif可用)

原理:利用fillType画出和背景色一致的圆角边框

class CornersView(context: Context, attrs: AttributeSet?) : ImageView(context, attrs) {

override fun onDraw(canvas: Canvas) {

super.onDraw(canvas)

canvas.save()

var mPaint = Paint()

mPaint.color = getParentBackGroundColor(parent)

var mPath = Path()

mPath.reset()

// add round rect

        mPath.setFillType(Path.FillType.INVERSE_EVEN_ODD)

var radius = dp2px(5f)

var mCorners =floatArrayOf(radius,radius,radius,radius,radius,radius,radius,radius)

mPath.addRoundRect(RectF(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat()), mCorners, Path.Direction.CCW)

canvas.drawPath(mPath, mPaint)

canvas.restore()

}

/**

* 获取父控件颜色

    * @param parent

    * @return

    */

    private fun getParentBackGroundColor(parent: ViewParent?): Int {

if (parent ==null) {

return Color.WHITE

        }

if (parentis View) {

val parentView = parentas View

val parentColor = getViewBackGroundColor(parentView)

if (parentColor != Color.TRANSPARENT) {

return parentColor

}else {

getParentBackGroundColor(parentView!!.parent)

}

}

return Color.WHITE

    }

/**

* 获取 View 的背景色

    * @param view

    * @return

    */

    private fun getViewBackGroundColor(view: View): Int {

val drawable = view.background

        if (drawable !=null) {

try {

val mField = drawable.javaClass.getDeclaredField("mColorState")

mField.isAccessible =true

                val mColorState = mField.get(drawable)

val mColorState_class = mColorState.javaClass

                val mColorState_field = mColorState_class.getDeclaredField("mUseColor")

mColorState_field.isAccessible =true

                val color = mColorState_field.get(mColorState)as Int

if (color != Color.TRANSPARENT) {

return color

}

}catch (e: Exception) {

e.printStackTrace()

}

}

return Color.TRANSPARENT

    }

private fun dp2px(dpValue: Float): Float {

val scale =context.resources.displayMetrics.density

        return dpValue * scale +0.5f

    }

}

你可能感兴趣的:(圆角View(ImageView,Gif可用))