Render the font onto a surface and store the surface into a sprite so we can do more complex stuff with it.
        (such as rotation and scale)
425000
def __render_onto_sprite(self):
        """"""
        font_surface = self.__font.render(self.__text, True, self.color)
        self.__font_sprite.apply_texture(font_surface)
        self.__font_sprite.center_origin()
101303
def draw_mathtext(self, gc, x, y, s, prop, angle):
        
        if __debug__: verbose.report('RendererAgg.draw_mathtext',
                                     'debug-annoying')
        ox, oy, width, height, descent, font_image, used_characters = \
            self.mathtext_parser.parse(s, self.dpi, prop)

        xd = descent * np.sin(np.deg2rad(angle))
        yd = descent * np.cos(np.deg2rad(angle))
        x = np.round(x + ox + xd)
        y = np.round(y - oy + yd)
        self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
202910
def surface_constructor(surface):
    """"""
    if NO_IMAGES:
        return

    ax = surface.plot(256, with_nodes=True)
    line = ax.lines[0]
    nodes = surface._nodes
    add_patch(ax, nodes[:, (0, 1, 2, 5)], line.get_color())
    delta = 1.0 / 32.0
    ax.text(
        nodes[0, 0],
        nodes[1, 0],
        r"$v_0$",
        fontsize=20,
        verticalalignment="top",
        horizontalalignment="right",
    )
    ax.text(
        nodes[0, 1],
        nodes[1, 1],
        r"$v_1$",
        fontsize=20,
        verticalalignment="top",
        horizontalalignment="center",
    )
    ax.text(
        nodes[0, 2],
        nodes[1, 2],
        r"$v_2$",
        fontsize=20,
        verticalalignment="top",
        horizontalalignment="left",
    )
    ax.text(
        nodes[0, 3] - delta,
        nodes[1, 3],
        r"$v_3$",
        fontsize=20,
        verticalalignment="center",
        horizontalalignment="right",
    )
    ax.text(
        nodes[0, 4] + delta,
        nodes[1, 4],
        r"$v_4$",
        fontsize=20,
        verticalalignment="center",
        horizontalalignment="left",
    )
    ax.text(
        nodes[0, 5],
        nodes[1, 5] + delta,
        r"$v_5$",
        fontsize=20,
        verticalalignment="bottom",
        horizontalalignment="center",
    )
    ax.axis("scaled")
    ax.set_xlim(-0.125, 1.125)
    ax.set_ylim(-0.125, 1.125)
    save_image(ax.figure, "surface_constructor.png")
755195
def get_font(self, face, bold=False, italic=False):
        """"""
        key = '%s-%s-%s' % (face, bold, italic)
        if key not in self._fonts:
            font = dict(face=face, bold=bold, italic=italic)
            self._fonts[key] = TextureFont(font, self._renderer)
        return self._fonts[key]
739649
def render_image(self, rgbobj, dst_x, dst_y):
        
        self.logger.debug("redraw surface=%s" % (self.surface))
        if self.surface is None:
            return
        self.logger.debug("drawing to surface")

        # Prepare array for rendering
        # TODO: what are options for high bit depth under Qt?
        data = rgbobj.get_array(self.rgb_order, dtype=np.uint8)
        (height, width) = data.shape[:2]

        daht, dawd, depth = data.shape
        self.logger.debug("data shape is %dx%dx%d" % (dawd, daht, depth))

        # Get qimage for copying pixel data
        qimage = self._get_qimage(data)
        drawable = self.surface

        painter = QPainter(drawable)
        #painter.setWorldMatrixEnabled(True)

        # fill surface with background color
        #imgwin_wd, imgwin_ht = self.viewer.get_window_size()
        size = drawable.size()
        sf_wd, sf_ht = size.width(), size.height()
        bg = self.viewer.img_bg
        bgclr = self._get_color(*bg)
        painter.fillRect(QtCore.QRect(0, 0, sf_wd, sf_ht), bgclr)

        # draw image data from buffer to offscreen pixmap
        painter.drawImage(QtCore.QRect(dst_x, dst_y, width, height),
                          qimage,
                          QtCore.QRect(0, 0, width, height))
1161046
def draw(self):
        
        if self.state > 0:
            self.renderer.draw_background(self.surface, self.layout.position, self.layout.size)
            for row in self.layout.rows:
                for key in row.keys:
                    self.renderer.draw_key(self.surface, key)
1286005
def render(self, surf):
        """"""
        if not self.flags & self.NO_SHADOW:
            circle(surf, self.center + self._bg_delta, self.width / 2, LIGHT_GREY)
        circle(surf, self.center + self._front_delta, self.width / 2, self._get_color())

        self.text.center = self.center + self._front_delta
        self.text.render(surf)
160808
function add() {
    var modifier = new Modifier({
        size: [200, 80],
        align: [0, 0],
        origin: [0, 0],
        transform: Transform.translate(100, 210)
    });

    var layout = new ({
        direction: Utility.Direction.X
    });

    var item1 = new ImageSurface({
        size: [80, 80],
        content: './images/famous_logo.png'
    });

    var item2 = new Surface({
        size: [120, 80],
        content: 'Example',
        properties: {
            textAlign: 'center',
            lineHeight: '80px',
            backgroundColor: '#eaeaea'
        }
    });

    layout.sequenceFrom([item1, item2]);
    ctx.add(modifier).add(layout);
}
104417
def draw_text(self, ax, text, force_trans=None, text_type=None):
        """"""
        content = text.get_text()
        if content:
            transform = text.get_transform()
            position = text.get_position()
            coords, position = self.process_transform(transform, ax,
                                                      position,
                                                      force_trans=force_trans)
            style = utils.get_text_style(text)
            self.renderer.draw_text(text=content, position=position,
                                    coordinates=coords,
                                    text_type=text_type,
                                    style=style, mplobj=text)
764152
def _init_glyph(self, plot, mapping, properties):
        
        properties = mpl_to_bokeh(properties)
        properties = dict(properties, **mapping)
        if 'xs' in mapping:
            renderer = plot.patches(**properties)
        else:
            renderer = plot.quad(**properties)
        if self.colorbar and 'color_mapper' in self.handles:
            self._draw_colorbar(plot, self.handles['color_mapper'])
        return renderer, renderer.glyph
135634
def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size):
    """"""
    # Necessary to flush commands before requesting current viewport because
    # There may be a set_viewport command waiting in the queue.
    # TODO: would be nicer if each canvas just remembers and manages its own
    # viewport, rather than relying on the context for this.
    canvas = context.get_current_canvas()
    canvas.context.flush_commands()

    text_vtype = np.dtype([('a_position', np.float32, 2),
                           ('a_texcoord', np.float32, 2)])
    vertices = np.zeros(len(text) * 4, dtype=text_vtype)
    prev = None
    width = height = ascender = descender = 0
    ratio, slop = 1. / font.ratio, font.slop
    x_off = -slop
    # Need to make sure we have a unicode string here (Py2.7 mis-interprets
    # characters like "•" otherwise)
    if sys.version[0] == '2' and isinstance(text, str):
        text = text.decode('utf-8')
    # Need to store the original viewport, because the font[char] will
    # trigger SDF rendering, which changes our viewport
    # todo: get rid of call to glGetParameter!
    orig_viewport = canvas.context.get_viewport()
    for ii, char in enumerate(text):
        glyph = font[char]
        kerning = glyph['kerning'].get(prev, 0.) * ratio
        x0 = x_off + glyph['offset'][0] * ratio + kerning
        y0 = glyph['offset'][1] * ratio + slop
        x1 = x0 + glyph['size'][0]
        y1 = y0 - glyph['size'][1]
        u0, v0, u1, v1 = glyph['texcoords']
        position = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]
        texcoords = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]]
        vi = ii * 4
        vertices['a_position'][vi:vi+4] = position
        vertices['a_texcoord'][vi:vi+4] = texcoords
        x_move = glyph['advance'] * ratio + kerning
        x_off += x_move
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        width += x_move
        height = max(height, glyph['size'][1] - 2*slop)
        prev = char
    # Also analyse chars with large ascender and descender, otherwise the
    # vertical alignment can be very inconsistent
    for char in 'hy':
        glyph = font[char]
        y0 = glyph['offset'][1] * ratio + slop
        y1 = y0 - glyph['size'][1]
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        height = max(height, glyph['size'][1] - 2*slop)

    if orig_viewport is not None:
        canvas.context.set_viewport(*orig_viewport)

    # Tight bounding box (loose would be width, font.height /.asc / .desc)
    width -= glyph['advance'] * ratio - (glyph['size'][0] - 2*slop)
    dx = dy = 0
    if anchor_y == 'top':
        dy = -ascender
    elif anchor_y in ('center', 'middle'):
        dy = -(height / 2 + descender)
    elif anchor_y == 'bottom':
        dy = -descender
    # Already referenced to baseline
    # elif anchor_y == 'baseline':
    #     dy = -descender
    if anchor_x == 'right':
        dx = -width
    elif anchor_x == 'center':
        dx = -width / 2.
    vertices['a_position'] += (dx, dy)
    vertices['a_position'] /= lowres_size
    return vertices
27597
def render(self, display):
        """"""
        # to handle changing objects / callable
        if self.text != self._last_text:
            self._render()

        display.blit(self._surface, (self.topleft, self.size))
241616
def render(self, display):
        """"""

        # to handle changing objects / callable
        if self.shawn_text != self._last_text:
            self._render()

        if self.text:
            papy = self._surface.get_width()
            if papy <= self.width:
                display.blit(self._surface, (self.topleft, self.size))
            else:
                display.blit(self._surface, (self.topleft, self.size), ((papy - self.w, 0), self.size))
        else:
            display.blit(self.default_text, (self.topleft, self.size))

        if self._focus:
            groom = self.cursor_pos()
            line(display, (groom, self.top), (groom, self.bottom), CONCRETE)
747264
def _init_glyph(self, plot, mapping, properties, key):
        
        properties = mpl_to_bokeh(properties)
        plot_method = '_'.join(key.split('_')[:-1])
        renderer = getattr(plot, plot_method)(**dict(properties, **mapping))
        return renderer, renderer.glyph
986765
def get_surface(shifts, orig_text, item, text):
    """"""
    span = item.span()
    logging.debug(u'\tInitial span: %s ("%s")', span, text[span[0]:span[1]])

    real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1])
    surface = orig_text[real_span[0]:real_span[1]]
    logging.debug(u'\tShifted span: %s ("%s")', real_span, surface)

    while any(surface.endswith(i) for i in [' ', '-']):
        surface = surface[:-1]
        real_span = (real_span[0], real_span[1] - 1)

    while surface.startswith(' '):
        surface = surface[1:]
        real_span = (real_span[0] + 1, real_span[1])

    logging.debug(u'\tFinal span: %s ("%s")', real_span, surface)
    return surface, real_span
359514
def _make_tile(self, value, background, text):
        """"""
        tile = pygame.Surface((self.cell_width, self.cell_height), pygame.SRCALPHA)
        pygame.draw.rect(tile, background, (0, 0, self.cell_width, self.cell_height))
        # The "zero" tile doesn't have anything inside.
        if value:
            label = load_font(self.BOLD_NAME, 50 if value < 1000 else
                              (40 if value < 10000 else 30)).render(str(value), True, text)
            width, height = label.get_size()
            tile.blit(label, ((self.cell_width - width) / 2, (self.cell_height - height) / 2))
        return tile
997243
def draw(self):
        
        if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying')

        self.renderer = self.get_renderer(cleared=True)
        # acquire a lock on the shared font cache
        RendererAgg.lock.acquire()

        try:
            self.figure.draw(self.renderer)
        finally:
            RendererAgg.lock.release()