1

I have this function that renders text in multiple lines in pygame and does not allow the width of the text to exceed a certain width. Latter in the script, inside the while loop, I am going to pass some random size text that I get from websockets inside this function so that it is rendered on screen. I want to know how can I acess inside the while loop the height of any specific text that is rendered by this function.

def display_text(surface,text,pos,font,color=(250,250,250)):

    collection = [word.split(' ') for word in text.splitlines()]
    space = font.size(' ')[0]
    x,y = pos
    for lines in collection:
        for words in lines:
            word_surface = font.render(words, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= screen_w-75:
                x = pos[0]
                y += word_height
            surface.blit(word_surface, (x,y))
            x += word_width + space
        x = pos[0]
        y += word_height

Claudio
  • 7,474
  • 3
  • 18
  • 48
  • Why do you repeat the question? [Get height of pygame text](https://stackoverflow.com/questions/74122742/get-height-of-pygame-text). Repeating questions to attract attention is not desirable – Rabbid76 Oct 19 '22 at 12:49
  • If you calculate the height in the rendering function (as a single value or a list) you can let the rendering function return this value(s) making it available within the while loop: `height = display_text(surface,text,pos,font)` . – Claudio Oct 19 '22 at 12:55
  • Add to your rendering function: `return y-pos[1]` for a single height value of all of the text. By the way: check if all words have the same height and/or track the maximum to decide about vertical spacing of the next line to avoid problems if the height of the last word in a line is lower compared to another word in this line. – Claudio Oct 19 '22 at 13:09
  • @Rabbid76: the duplicate links do not answer the question. They provide only code so similar to the code by the OP that you may think it was copied from that links and modified to fit own purpose. – Claudio Oct 19 '22 at 13:25
  • @Claudio I'm of different opinion. The duplicates explain exactly how to render multiline text with pygame. One of the duplicates has 10 answers, that's where you should start. – Rabbid76 Oct 19 '22 at 13:29
  • @Rabbid76 sorry, but I felt that I hadn´t phrased my question properly – Afonso Neves Oct 19 '22 at 14:37
  • @AfonsoNeves In this case you should edit the original question, but not ask a new question. You can still undelete and edit the original question. – Rabbid76 Oct 19 '22 at 15:00

0 Answers0