Search code examples
androidandroid-canvasandroid-custom-viewdrawtext

Draw Text using Canvas without using TextView object


I want to create a custom view. That view will be having a Text which is drawn using canvas. The text drawn does not uses any TextView object.

I tried to draw a text using canvas. Here is my code :

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
class CustomView(context: Context , attributeSet: AttributeSet) : View(context,attributeSet) {
    private val paint: Paint = Paint().apply {
        style = Paint.Style.FILL
        color = Color.WHITE
        textSize = 30f
        textAlign = Paint.Align.CENTER
        isAntiAlias = true
    }
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawText("Custom View",0f,0f,paint)
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.shaheen.drawtext.CustomView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

I tried this code but the text is not drawn in that view. it is showing a blank screen.


Solution

  • By doing this, the text was drawn. Here, I've changed the color of the paint to Black color

    private val paint: Paint = Paint().apply {
            style = Paint.Style.FILL_AND_STROKE
            color = Color.BLACK
            textSize = headingTextSize
            textAlign = Paint.Align.LEFT
            typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
            isAntiAlias = true
    
    }