将textView渲染到视图上

时间:2015-10-15 18:06:08

标签: android canvas text view textview

我有一个扩展View的课程。

在那个课程中,我画了一个纯白色的屏幕,然后想在上面画一些文字:

我已经使用textView和canvas.drawText尝试了这个,但是我无法获取任何要呈现的文本。知道问题是什么吗?

public class MyView extends View{

    Paint myPaint;
    Paint textPaint;
    Rect background;
    RelativeLayout layout;
    TextView text;

    public myView(Context context, int width, int height){

        myPaint = new Paint();        
        myPaint.setColor(Color.WHITE);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);

        background = new Rect(0, 0, width, height);

        layout = new RelativeLayout(context);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,    LayoutParams.MATCH_PARENT));

        text = new TextView(context);
        text.setTextColor(Color.BLACK);
        text.setSize(20);
        text.setText("Test");

        layout.addView(layout);

    }

   @Override
   public void onDraw(Canvas canvas){

       canvas.drawRect(background, myPaint);   //This draws OK 

       layout.draw(canvas); //Text doesn't draw

       canvas.drawText("Test", 0, 0, textPaint); //This also doesn't draw

   }
}

1 个答案:

答案 0 :(得分:1)

您正在将myPaint设置为黑白两种,而根本不设置textPaint颜色。同样对于文本绘画我相信你也需要设置文本大小。所以改变这些方面:

textPaint = new Paint();
myPaint.setColor(Color.BLACK);

进入这个:

textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(20);

编辑:

将原点放在0,0以外的其他位置。例如:

canvas.drawText("Test", 100, 100, textPaint);