首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在GdkPixbuf.Pixbuf上呈现文本

如何在GdkPixbuf.Pixbuf上呈现文本
EN

Stack Overflow用户
提问于 2014-07-27 08:46:37
回答 1查看 1.3K关注 0票数 2

我试图使用Python和Gdk 3向Pixbuf添加文本。

我已经在网上搜索了几个小时关于这个主题的信息,看起来我需要从像素创建一个开罗上下文。不幸的是,我对cairo没有任何经验,但我能够将这段代码组合在一起:

代码语言:javascript
复制
from gi.repository import Gdk

def put_text(pixbuf, text, x, y):
    #create a Gdk.Window
    window_attr= Gdk.WindowAttr()
    window_attr.width= pixbuf.get_width()
    window_attr.height= pixbuf.get_height()
    window_attr.window_type= Gdk.WindowType.OFFSCREEN
    #~ window_attr.window_type= Gdk.WindowType.TEMP
    window_attr.redirect= True
    #~ window_attr.redirect= False
    window= Gdk.Window(None, window_attr, Gdk.WindowAttributesType(0))

    #make a cairo context from the window
    context= Gdk.cairo_create(window)
    Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)

    #render text
    context.move_to(x, y)
    context.set_font_size(15)
    context.show_text(text)

    #get the resulting pixbuf
    surface= context.get_target()
    result= Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height())

    #~ window.destroy()
    return result

至少不会让我的程序崩溃。然而,它产生的像素点是完全透明的。有人能告诉我我做错了什么或者有什么更好的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-06 08:10:00

我终于成功地生成了工作代码。显然,使用from gi.repository import cairo是一个很大的错误。

代码语言:javascript
复制
from gi.repository import Gdk
import cairo

def put_text(pixbuf, text, x, y):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
    context = cairo.Context(surface)

    Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
    context.paint() #paint the pixbuf

    #add the text
    fontsize= 20
    context.move_to(x, y+fontsize)
    context.set_font_size(fontsize)
    context.set_source_rgba(0,0,0,1)
    context.show_text(text)

    #get the resulting pixbuf
    surface= context.get_target()
    pixbuf= Gdk.pixbuf_get_from_surface(surface, 0, 0, surface.get_width(), surface.get_height())

    return pixbuf
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24979367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档