0

Ι want to insert new line to my String to draw my Text on Canvas , but i cant figure it out , it is being drawn all the way horizontally. I tried using an XML resource and converting from integer. Also double backslash or forthslash. Nothing. Anything wrong with the canvas? Any help appreciated

 private Paint myPaint;
 private String myText;
 myPaint = new Paint();
 myPaint.setTextAlign(Paint.Align.CENTER);
 myPaint.setTypeface(Typeface.DEFAULT_BOLD);
 myPaint.setTextSize(25);

 myText = "FIRST PART\nSECOND PART\nTHIRD PART\nFOURTH PART";
 @Override
 protected void onDraw(Canvas canvas) {
    canvas.drawText(myText,canvas.getWidth()/2,canvas.getHeight()/3,myPaint);
}

1 Answers1

2

The drawText will not honor \n entries.

You need to draw text 3 times and increment the height by the height of the font ( display metrics ).

mjstam
  • 1,049
  • 1
  • 6
  • 5
  • thank all , drawing it 3 times is working perfeclty. – Ιγνάτιος Γληνός Jan 20 '15 at 09:20
  • @ΙγνάτιοςΓληνός No, no, no don't do that, see http://stackoverflow.com/a/8369690/2252830 – pskink Jan 20 '15 at 11:48
  • 1
    @ΙγνάτιοςΓληνός use a StaticLayout, it not only can draw several lines of text but also it automatically breakes your text into multiple lines and finally it can draw rich text aka spans e. g. ForegroundColorSpan, BackgroundColorSpan etc – pskink Jan 20 '15 at 16:55
  • I don't think drawing 3 lines is a terrible solution. That said, I did not know about StaticLayout...nice. – mjstam Jan 20 '15 at 18:00
  • @mjstam it is, since you have to break your text into multiple lines and most likely you will not do that in the optimal way... – pskink Jan 20 '15 at 18:09
  • Tried this (text is array and is length is 2 for two lines separated by \n): for (int loop = 0; loop < text.length; loop++) { textCanvas.drawText(text[loop], 0, (Math.abs(fontMetrics.top) + fontMetrics.bottom) * (loop + 1), paint); } Its giving two lines but with less spacing . – Ravi Yadav Mar 26 '19 at 13:45