Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Created January 12, 2022 17:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/43e18e64c0ee2766d5122a66e1a61c9a to your computer and use it in GitHub Desktop.
Save hrules6872/43e18e64c0ee2766d5122a66e1a61c9a to your computer and use it in GitHub Desktop.
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