class CircleColorImageView : AppCompatImageView {

    private lateinit var paint: Paint

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    private fun init() {
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.run {
            style = Paint.Style.FILL
            color = Color.TRANSPARENT
        }
    }

    fun setColor(resId: Int) {
        paint.run {
            color = resId
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        val x = canvas?.width ?: 0
        val y = canvas?.height ?: 0

        if (x == 0 || y == 0) {
            return
        }

        val half = (x / 2).toFloat() // 정확한 원이기 때문에 x/2, y/2, radius 값이 같아서 이렇게 처리해도 무방함

        canvas?.drawCircle(half, half, half, paint)
    }
}
by Invincible Cooler 2020. 3. 6. 17:16