Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot draw text to custom view

I'm having an issue using the canvas.drawText() method.

I have a custom view, as follows:

public class PagerIndicator extends View
{
    @Override
    public void onDraw(Canvas canvas)
    {       
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.GRAY);
    canvas.drawPaint(paint);

    paint.setColor(Color.WHITE);
    paint.setTextSize(10);
    paint.setAntiAlias(true);
    paint.setTextAlign(Align.LEFT);
    canvas.drawText("TEST", 0, 0, paint);
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ysi.crm.PagerIndicator
    android:id="@+id/swipe_page_indicator"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

The drawPaint() method is working, I can see the gray paint when I test. However, canvas.drawText() is not drawing. I see no text on top of the gray.

I've beat this thing to death, I could find no one else who's had this problem, much less a solution. I would be very grateful for any help.

like image 857
bwiechart Avatar asked Feb 15 '26 16:02

bwiechart


2 Answers

I ran into this before. The coordinate that you set it to draw with is not the top left coordinate of the text. It is the bottom left coordinate of the text.

Because of this, your text is probably being drawn above the top of your view.

like image 134
Shellum Avatar answered Feb 18 '26 05:02

Shellum


Try this:

public class PagerIndicator extends View
{
    @Override
    public void onDraw(Canvas canvas)
    {       
    Paint paint1 = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.GRAY);
    canvas.drawPaint(paint1);

    Paint paint2 = new Paint();
    paint2.setColor(Color.WHITE);
    paint2.setTextSize(10);
    paint2.setAntiAlias(true);
    paint.setTextAlign(Align.LEFT);
    canvas.drawText("TEST", 0, 0, paint2);
}
like image 23
jsaye Avatar answered Feb 18 '26 06:02

jsaye