Unable to draw text in custom view

I am having a problem using the canvas.drawText () method.

I have a custom view:

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>

      

DrawPaint () method works , I see gray paint when testing. However canvas.drawText () doesn't draw. I can't see text over gray.

I beat this thing to death, I couldn't find anyone else who had this problem, much less a solution. I would be very grateful for any help.

+3


source to share


3 answers


I've encountered this before. The coordinate you set for drawing is not the top left coordinate of the text. This is the bottom left coordinate of the text.



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

+8


source


Try the following:



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);
}

      

+1


source


Change this line:

canvas.drawText("TEST", 0, 0, paint2);

      

to:

canvas.drawText("TEST", 100, 100, paint2);

      

+1


source







All Articles