【问题标题】:Pyglet draw text into texturePyglet 将文本绘制到纹理中
【发布时间】:2017-11-20 03:00:02
【问题描述】:

我正在尝试使用 Pyglet 使用 OpenGL 渲染图像。到目前为止,我已经能够设置帧缓冲区和纹理,渲染到其中并将其保存为 PNG 图像。但是我不知道如何使用 Pyglets 字体渲染。

import numpy as np
import pyglet
from pyglet.gl import *
from ctypes import byref, sizeof, POINTER

width = 800
height = 600
cpp = 4

# Create the framebuffer (rendering target).
buf = gl.GLuint(0)
glGenFramebuffers(1, byref(buf))
glBindFramebuffer(GL_FRAMEBUFFER, buf)

# Create the texture (internal pixel data for the framebuffer).
tex = gl.GLuint(0)
glGenTextures(1, byref(tex))
glBindTexture(GL_TEXTURE_2D, tex)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, None)

# Bind the texture to the framebuffer.
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0)

# Something may have gone wrong during the process, depending on the
# capabilities of the GPU.
res = glCheckFramebufferStatus(GL_FRAMEBUFFER)
if res != GL_FRAMEBUFFER_COMPLETE:
  raise RuntimeError('Framebuffer not completed')

glViewport(0, 0, width, height)

# DRAW BEGIN
# =====================
glClearColor(0.1, 0.1, 0.1, 1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 0.5, 0.02)
glRectf(-0.75, -0.75, 0.75, 0.75)

glColor3f(1.0, 1.0, 1.0)
label = pyglet.text.Label(
  "Hello, World", font_name='Times New Roman', font_size=36,
  x=0, y=0, anchor_x='center', anchor_y='center')
label.draw()
# =====================
# DRAW END

# Read the buffer contents into a numpy array.
data = np.empty((height, width, cpp), dtype=np.float32)
glReadPixels(0, 0, width, height, GL_RGBA, GL_FLOAT, data.ctypes.data_as(POINTER(GLfloat)))

# Save the image.
import imageio
data = np.uint8(data * 255)
imageio.imwrite("foo.png", data)

文本没有出现在帧缓冲区中。如何在帧缓冲区上渲染标签?

【问题讨论】:

    标签: python opengl pyglet text-rendering


    【解决方案1】:

    为了在 Pyglet 中渲染标签,首先应该设置一个正交投影。在给定的示例中,请执行以下操作:

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, width, 0, height, -1, 1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glColor3f(1.0, 1.0, 1.0)
    label = pyglet.text.Label(
      "Hello, World", font_name='Times New Roman', font_size=36,
      x=width/2, y=height/2, anchor_x='center', anchor_y='center')
    label.draw()
    

    然后,标签按预期呈现。 (注:将标签的偏移量移动到图片中心,即x=width/2, y=height/2,

    foo.png (output framebuffer image)

    【讨论】:

    • 谢谢你的作品!只需将0, height 参数切换为glOrtho() 即可垂直翻转图像。 :)
    • 整洁!或者,我认为您会在转储帧缓冲区后翻转图像。类似于 -- data = np.flipud(data)glReadPixels() 之后。
    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多