pygobject / pycairo

Python bindings for cairo
https://pycairo.readthedocs.io
Other
633 stars 86 forks source link

how could I draw vertical text in cairo ? #246

Open duwangthefirst opened 2 years ago

duwangthefirst commented 2 years ago

I've implemented horizontal text rendering, the code is as below: (but how could I draw text vertically(not rotating for 90 or 270 degree))

截屏2021-12-30 上午10 55 17
import cairo
from math import pi

def draw_horizontal_text(context, text, x0, y0, font_size, font_color=(0, 0, 0, 1), font_family="Source Han Mono SC"):
    context.move_to(x0, y0)
    context.select_font_face(font_family, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
    context.set_font_size(font_size)
    x_bearing, y_bearing, width, height, x_advance, y_advance = context.text_extents(text)
    context.move_to(x0-x_bearing, y0-(height+y_bearing))
    context.set_source_rgba(*font_color)
    context.show_text(text)

def demo():
    width = 2000
    height = 2000
    surface = cairo.PDFSurface("result.pdf", width, height)
    context = cairo.Context(surface)
    context.scale(width, height)
    draw_horizontal_text(context, "你吃饭了没啊aAg", 0.1, 0.9, 0.1)

if __name__ == '__main__':
    demo()
naveen521kk commented 2 years ago

I don't think it's possible to do with plain pycairo, instead, you should use something like Pango for doing it. Also, I don't think there exists any binding for Pango with Python that can be used with pycairo. I think something like cairocffi + pangocairocffi can be used, I could see an example here.

hth

ldo commented 2 years ago

This is really a job for a text-shaping library like HarfBuzz.

Relevant example use of my Python binding for HarfBuzz here, output from that example here.