I am creating a Custom TextView where i want to have a circle background and in the middle i want to have the initials of the text. The code is the below
class CircleTextView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
private lateinit var circlePaint: Paint
private lateinit var strokePaint: Paint
private fun initViews(context: Context, attrs: AttributeSet) {
circlePaint = Paint()
strokePaint = Paint()
circlePaint.apply {
color = Color.parseColor("#041421")
style = Paint.Style.FILL
flags = Paint.ANTI_ALIAS_FLAG
isDither = true
}
strokePaint.apply {
color = Color.parseColor("#fe440b")
style = Paint.Style.FILL
flags = Paint.ANTI_ALIAS_FLAG
isDither = true
}
}
override fun draw(canvas: Canvas) {
val diameter: Int
val h: Int = this.height
val w: Int = this.width
diameter = h.coerceAtLeast(w)
val radius: Int = diameter / 2
canvas.drawCircle(
radius.toFloat(), radius.toFloat(), radius.toFloat(), strokePaint
)
canvas.drawCircle(
radius.toFloat(), radius.toFloat(), (radius - 10).toFloat(), circlePaint
)
super.draw(canvas)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val dimension = widthMeasureSpec.coerceAtLeast(heightMeasureSpec)
super.onMeasure(dimension, dimension)
}
init {
initViews(context, attrs)
setWillNotDraw(false)
}
}
Inside my activity xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary">
<com.example.ui.views.CircleTextView
android:id="@+id/circleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@color/colorWhite"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /> />
</androidx.constraintlayout.widget.ConstraintLayout>
and in the Kotlin file
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
circleText.apply {
text = "II"
setPadding(50, 50, 50, 50)
}
}
My problem here is that the View seems to gets cropped on the right side of it and also the Text with the letters is not in the Center of the view.
How can i solve that?