2

这是我的代码:

进口开罗
导入操作系统
从 PIL 导入图像

图像大小 = (512,128)
表面 = cairo.ImageSurface(cairo.FORMAT_ARGB32, *imagesize)

cr = cairo.Context(表面)

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)

...

surface.write_to_png("MyImage.png")

如您所见,我正在为这个 PNG 绘制一些白色文本,但背景默认为不透明的黑色。如何使 png 透明以便只显示白色文本?

4

1 回答 1

7

我能够使用 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")
于 2013-02-17T05:20:06.423 回答