Multiline surfaceView.drawText

Tutorials concerning the OpenGL® ES cross-platform API for full-function 2D and 3D graphics on the Google-Android platform.

Multiline surfaceView.drawText

Postby lamellama » Mon May 02, 2011 6:10 pm

I have been using surfaceview classes drawtext function but was surprised it only supports drawing a single line and I thought I'd share my solution, I have not included the entire class but hopefully it is not too hard to follow.

It works by looping through each word and checking if that words width fits within the defined boundary if not it counts the current number of characters for that line and starts the next.

Code: Select all
         mText = new String("Balls are not to be played with");
         mTextSize = 25;
         mPaintWhiteText = new Paint();
         mTextWidths = new float[mText.length()];
         mPaintWhiteText.getTextWidths(mText, mTextWidths);

         float lineWidthCount = 0;
         mLineCount = 1;
         mLineCharacterCount[0] = 0;
         float wordWidth = 0;
         int i, j;

         for(i=0 ; i < mText.length(); i++){
            j = i;
            while((!mText.regionMatches(j, " ", 0, 1))&&(j < mText.length())){
               lineWidthCount += mTextWidths[j];
            if(lineWidthCount >= RightTextBoundary){
               mLineCharacterCount[mLineCount] = i;
               lineWidthCount = 0;
               mLineCharacterCount[mLineCount] = j;
               i = j;
         mLineCharacterCount[mLineCount] =  mText.length();

Code: Select all
public void draw(Canvas c){
   for(int i = 0; i < mLineCount ; i++){
      c.drawText(mText, mLineCharacterCount[i], mLineCharacterCount[i+1], mWidth, mTextSize+(mTextSize*i), mPaintWhiteText);
Posts: 2
Joined: Wed Jan 26, 2011 11:12 pm


Re: Multiline surfaceView.drawText

Postby ekremk » Tue Jun 25, 2013 1:21 pm

@Freshman what is the type of mLineCharacterCount?
Once Poster
Once Poster
Posts: 1
Joined: Tue Jun 25, 2013 1:19 pm


Return to Android 2D/3D Graphics - OpenGL Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest