Created
January 12, 2022 17:57
-
-
Save hector6872/43e18e64c0ee2766d5122a66e1a61c9a to your computer and use it in GitHub Desktop.
Circle View for Android in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="CircleView"> | |
<attr name="cv_color" format="color" /> | |
</declare-styleable> | |
</resources> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = [email protected] | |
}) | |
} | |
} | |
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