我能够使用 set_source_rgba() 设置透明背景并使用 0.0 作为 alpha 值:
cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
cr.rectangle(0, 0, 512, 128)
cr.fill()
然后,我还必须确保使用以下内容编写文本:
# set writing color to white
cr.set_source_rgb(1, 1, 1)
# write text
cr.move_to(100,50)
cr.show_text("hello")
# commit to surface
cr.stroke()
这是对我有用的完整代码:
import os
from PIL import Image
imagesize = (512,128)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)
cr = cairo.Context(surface)
# paint background
cr.set_source_rgba(0.0, 0.0, 0.0, 0.0) # transparent black
cr.rectangle(0, 0, 512, 128)
cr.fill()
# setup font
cr.select_font_face("Verdana", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(24)
cr.set_source_rgb(1, 1, 1)
# write with font
cr.move_to(100,50)
cr.show_text("hello")
# commit to surface
cr.stroke()
# save file
surface.write_to_png("MyImage.png")