Search code examples
pango

Text with spaces split to new line when using pango_layout


I am new to the Embedded Linux. I am trying to display a string text different alignments. But when I use the Pango. It aligned correctly for the single words without space characters in it. But some my string contains spaces to separate words. But it aligned int the new line when using the pango_layout. I am running my application in Ubuntu using GCC as the compiler and the system include directory shows pongo-1.0.

And my code is given below

 pLayOut = pango_cairo_create_layout(pCntxt);
   pango_layout_set_text(pLayOut, "Sample text #1", -1);
   desc = pango_font_description_from_string(font);
   pango_layout_set_font_description(pLayOut, desc);
   pango_font_description_free(desc);

   cairo_set_source_rgb(pCntxt, rgbRed,rgbGreen, rgbBlue);

   //Set width of the layout to align correctly
   cairo_text_extents(pCntxt, "Sample text #1", &extents);
   pango_layout_set_width(pLayOut, extents.width);

   cairo_move_to(pCntxt, pPar->tpUlX, pPar->tpUlY);
   pango_layout_set_alignment(pLayOut, pPar->tpAlign);

   pango_cairo_update_layout(pCntxt, pLayOut);
   pango_cairo_show_layout(pCntxt, pLayOut);

The output of the left alignment

Sample 
text 
#1

The output of right alignment

 Sample 
   text 
     #1 

How I can draw this in one line using Pango layout? I tried several other options in Pango layout but no luck

I want my text like this

              Sample text #1//Using left align
Sample text #1  //Using right align
            X,Y location here

Solution

  • In an edit, you added this to your question:

    I want my text like this

                  Sample text #1//Using left align
    Sample text #1  //Using right align
                X,Y location here
    

    That's not how alignment works in cairo. Imagine a sheet of paper on which you write "Hello". Left-alignment means that this is written near the left edge of the paper. Right-alignment refers to the right edge.

    As an 'image', where | refers to the edge of the paper:

    | Hello       |
    |       Hello |
    

    A bit more technical: The left edge is specified by the X/Y position. The right edge is specified relative to that by the width. So, the left edge is at x and the right at x+width.

    To do the style of right alignment that you are asking for, you have to compute the right position yourself. You can do that with pango_layout_get_pixel_extents(). You want the logical extents (second argument). You then want to draw your text at an x position of x-width. That should produce the alignment that you are looking for.