Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Circle View for Android in Kotlin
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleView">
<attr name="cv_color" format="color" />
</declare-styleable>
</resources>
class CircleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private val paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } }
@ColorInt
var color: Int = Color.TRANSPARENT
set(value) {
field = value
invalidate()
}
init {
attrs?.use(context, R.styleable.CircleView) {
color = getColor(R.styleable.CircleView_cv_color, color)
}
}
override fun onDraw(canvas: Canvas?) = super.onDraw(canvas).also {
canvas?.drawCircle(width.div2float(), height.div2float(), min(width, height).div2float(), paint.apply {
color = this@CircleView.color
})
}
}
private fun Int.div2float() = (this / 2).toFloat()
inline fun AttributeSet.use(context: Context, @StyleableRes attrs: IntArray, block: TypedArray.() -> Unit) {
context.obtainStyledAttributes(this, attrs).use { typedArray -> block(typedArray) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment