[cairo] cairo_show_text and Chinese

Behdad Esfahbod behdad at behdad.org
Thu Jul 24 11:01:46 PDT 2008


On Wed, 2008-07-16 at 22:07 -0700, Carl Worth wrote:
> On Mon, 2008-07-07 at 15:18 +1200, Robert O'Callahan wrote:
> 
> > If you want to render non-ASCII text then you should really stop using the cairo "toy text" APIs and start using a higher level text API like Pango. See http://cairographics.org/manual/cairo-Text.html... This should be in the FAQ too.
> 
> Yes, we definitely need a new question answered there:
> 
> 	I've been using cairo_show_text, but I want to start doing more
> 	complex things than it can do. How can I switch to using pango
> 	instead?
> 
> And the answer would have before and after snippets of code.
> 
> Behdad, want to write up that answer for us? If you'd like to just post
> a reply to this message, I'd be glad to put the answer into the FAQ page
> on the wiki.

It will become much simpler in the future, but for now:

Minimal cairo text example:

================================
# -*-coding=utf8-*-
import cairo

unicode_string = "Test"
filename = "out.png"
width = 200
height = 200

surface = cairo.ImageSurface (cairo.FORMAT_RGB24, width, height)
cr = cairo.Context (surface)

cr.set_source_rgb (1, 1, 1)
cr.paint ()

cr.set_source_rgb (0, 0, 0)
cr.set_font_face (font_face)
cr.set_font_size (18)
cr.move_to (100, 100)
cr.show_text (unicode_string)

surface.write_to_png (filename)
================================

Minimal pangocairo text example:

===============================
# -*-coding=utf8-*-
import pango, cairo, pangocairo

unicode_string = "ﺐﻫﺩﺍﺩ"
filename = "out.png"
width = 200
height = 200

surface = cairo.ImageSurface (cairo.FORMAT_RGB24, width, height)
cr = pangocairo.CairoContext (cairo.Context (surface))

cr.set_source_rgb (1, 1, 1)
cr.paint ()

cr.set_source_rgb (0, 0, 0)

layout = cr.create_layout ()
layout.set_font_description (pango.FontDescription ("Sans 18px"))
layout.set_text (unicode_string)
cr.move_to (100, 100)
cr.show_layout (layout)

surface.write_to_png (filename)
===============================

That has a different text placement from the cairo one though.  To get
the same text origin as cairo (baseline left, instead of Pango's top
left), replace the show_layout line with this:

cr.show_layout_line (layout.get_line (0))


> -Carl

Cheers,
-- 
behdad
http://behdad.org/

"Those who would give up Essential Liberty to purchase a little
 Temporary Safety, deserve neither Liberty nor Safety."
        -- Benjamin Franklin, 1759



More information about the cairo mailing list