multilabel.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. import pygame
  3. class MultiLabel: ##Multi Line Label
  4. _PosX=0
  5. _PosY=0
  6. _Width=135
  7. _Height=100
  8. _Text=""
  9. _FontObj=None
  10. _Color = pygame.Color(83,83,83)
  11. _CanvasHWND = None
  12. _TextSurf = None
  13. _MaxWidth = 0
  14. def __init__(self):
  15. pass
  16. def Init(self,text,font_obj,color=pygame.Color(83,83,83)):
  17. self._Color = color
  18. self._FontObj = font_obj
  19. self._Text = text
  20. self.blit_text(self._CanvasHWND,self._Text,(self._PosX,self._PosY),self._FontObj)
  21. def NewCoord(self,x,y):
  22. self._PosX = x
  23. self._PosY = y
  24. def SetColor(self,color):
  25. self._Color = color
  26. def GetText(self):
  27. return self._Text
  28. def SetText(self,text):
  29. self._Text = text
  30. self.blit_text(self._CanvasHWND,self._Text,(self._PosX,self._PosY),self._FontObj)
  31. def Width(self):
  32. return self._Width
  33. def SetCanvasHWND(self,_canvashwnd):
  34. self._CanvasHWND = _canvashwnd
  35. def blit_text(self, surface,text, pos, font):
  36. color = self._Color
  37. words = [word.split(' ') for word in text.splitlines()]
  38. space = font.size(' ')[0]
  39. max_width = self._Width
  40. x ,y = pos
  41. row_total_width = 0
  42. lines = 0
  43. for i,line in enumerate(words[:4]):
  44. for word in line[:12]:
  45. word_surface = font.render(word, True, color)
  46. word_width = word_surface.get_width()
  47. word_height = word_surface.get_height()
  48. row_total_width += word_width
  49. if row_total_width+space >= max_width:
  50. x = pos[0] # Reset the x.
  51. y += word_height # Start on new row.
  52. row_total_width = word_width
  53. if lines == 0:
  54. lines += word_height
  55. else:
  56. lines += word_height
  57. surface.blit(word_surface, (x, y))
  58. x += word_width + space
  59. x = pos[0] # Reset the x.
  60. y += word_height # Start on new row.
  61. lines += word_height
  62. self._Height = lines
  63. def Draw(self):
  64. #my_text = self._FontObj.render( self._Text,True,self._Color)
  65. self.blit_text(self._CanvasHWND,self._Text,(self._PosX,self._PosY),self._FontObj)
  66. #pygame.draw.rect(self._CanvasHWND,(83,83,83), (self._PosX,self._PosY,self._Width,self._Height) , 1 )
  67. #self._CanvasHWND.blit(my_text,(self._PosX,self._PosY,self._Width,self._Height))