def size(self, text): """Font.size(text): return (width, height) determine the amount of space needed to render text""" if not isinstance(text, (bytes_, unicode_)): raise TypeError("text must be a string or unicode") if isinstance(text, unicode_): text = text.encode('utf-8', 'replace') w = ffi.new("int*") h = ffi.new("int*") ecode = sdl.TTF_SizeUTF8(self._sdl_font, text, w, h) if ecode == -1: raise SDLError(ffi.string(sdl.TTF_GetError())) return int(w[0]), int(h[0])
def render(self, text, antialias, color, background=None): """Font.render(text, antialias, color, background=None): return Surface draw text on a new Surface""" color = Color(color) fg = ffi.new("SDL_Color [1]") bg = ffi.new("SDL_Color [1]") fg[0].r = color.r fg[0].g = color.g fg[0].b = color.b if background: try: background = Color(background) bg[0].r = background.r bg[0].g = background.g bg[0].b = background.b except (TypeError, ValueError): # Same error behaviour as pygame bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 else: bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 if text is None or text == '': # Just return a surface of width 1 x font height height = sdl.TTF_FontHeight(self._sdl_font) surf = Surface((1, height)) if background and isinstance(background, Color): surf.fill(background) else: # clear the colorkey surf.set_colorkey(flags=sdl.SDL_SRCCOLORKEY) return surf if not isinstance(text, (bytes_, unicode_)): raise TypeError("text must be a string or unicode") if isinstance(text, unicode_): text = text.encode('utf-8', 'replace') if utf_8_needs_UCS_4(text): raise UnicodeError( "A Unicode character above '\\uFFFF' was found;" " not supported") if b'\x00' in text: raise ValueError("A null character was found in the text") if antialias: if background is None: sdl_surf = sdl.TTF_RenderUTF8_Blended(self._sdl_font, text, fg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Shaded(self._sdl_font, text, fg[0], bg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Solid(self._sdl_font, text, fg[0]) if not sdl_surf: raise SDLError(ffi.string(sdl.TTF_GetError())) surf = Surface._from_sdl_surface(sdl_surf) if not antialias and background is not None: surf.set_colorkey() surf.set_palette([(bg[0].r, bg[0].g, bg[0].b)]) return surf