How to draw text on canvas?

前端 未结 3 1705
南笙
南笙 2020-12-13 18:28

i\'m trying to develop a simple pie chart class for android. For now, it can take a map of labels and values and draw the pie chart. I\'m yet to add the legends for the pie,

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 18:42

    Another (arguably better) way to draw text on a canvas is to use a StaticLayout. This handles multiline text when needed.

    String text = "This is some text.";
    
    TextPaint textPaint = new TextPaint();
    textPaint.setAntiAlias(true);
    textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
    textPaint.setColor(0xFF000000);
    
    int width = (int) textPaint.measureText(text);
    StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
    staticLayout.draw(canvas);
    

    The TextPaint and StaticLayout were instantiated right before being used here for the sake of illustration. Doing so in onDraw would hurt performance, though. Here is a better example showing them in the context of a custom view that draws it's own text.

提交回复
热议问题