问题
I'm new to pyglet. I'd like to change a pixel from black to white at each on_draw
iteration. So after 1000 iterations, there should be exactly 1000 white pixels in the window. However, I'd like to avoid calling 1000 draw operations in on_draw
for that. So I'd like to create an image, do an RGB putpixel on the image, and blit the image to the screen. How can I do that? The pyglet documentation, the examples and the source code aren't too helpful on this.
回答1:
Since no one gave a really good answer to this.
I'll place one here:
import pyglet
from random import randint
width, height = 500, 500
window = pyglet.window.Window(width=width, height=height)
image = pyglet.image.SolidColorImagePattern((255,255,255,255)).create_image(width, height)
data = image.get_image_data().get_data('RGB', width*3)
new_image = b''
for i in range(0, len(data), 3):
pixel = bytes([randint(0,255)]) + bytes([randint(0,255)]) + bytes([randint(0,255)])
new_image += pixel
image.set_data('RGB', width*3, new_image)
@window.event
def on_draw():
window.clear()
image.blit(0, 0)
pyglet.app.run()
Essentially, what this does is it creates a white image, that in itself can be drawn in the window. But seeing as we want to do putpixel
, i've modified every pixel in the white image as a demo.
Can be used in junction with:
- https://pythonhosted.org/pyglet/api/pyglet.image.ImageData-class.html#get_region
Which can be used to optemize the image manipulation further.
回答2:
This is too late to help you, but there are ways to do this. For example, blit_into, which modifies a loaded image:
import pyglet
window = pyglet.window.Window(600, 600)
background = pyglet.resource.image('my600x600blackbackground.bmp')
pix = pyglet.resource.image('singlewhitepixel.bmp').get_image_data()
def update(dt):
background.blit_into(pix, x, y, 0) #specify x and y however you want
@window.event
def on_draw():
window.clear()
background.blit(0,0)
pyglet.clock.schedule(update, 1.0/30) #30 frames per second
pyglet.app.run()
回答3:
Since I didn't get any answers, it seems there is no easy way to do this in pyglet. So I've given up on using pyglet.
来源:https://stackoverflow.com/questions/4532008/putpixel-with-pyglet