-1

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.

Shaheen Ahamed S
  • 176
  • 2
  • 11
  • The `drawText()` method is slightly different than the other draw methods. The y-coordinate is for the _baseline_ of the text, rather than the top. You're possibly not seeing the text because it's being drawn off-screen. Shift that down some, by at least the text size. – Mike M. Aug 27 '19 at 05:38
  • 1
    Please check this https://stackoverflow.com/questions/16861619/how-to-draw-text-inside-custom-view – Deepak S. Gavkar Aug 27 '19 at 05:39

1 Answers1

0

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

}
Shaheen Ahamed S
  • 176
  • 2
  • 11