Pygame: Draw single pixel

China☆狼群 提交于 2020-01-01 04:22:26

问题


I'm looking for method that allow me to draw single pixel on display screen. For example when I click mouse, I want the position of clicked pixel to change color. I know how to read mouse pos, but I could not find simple pixel draw ( there is screen.fill method but it's not working as I want).


回答1:


You can do this with surface.set_at():

surface.set_at((x, y), color)

You can also use pygame.gfxdraw.pixel():

from pygame import gfxdraw
gfxdraw.pixel(surface, x, y, color)

Do note, however, the warning:

EXPERIMENTAL!: meaning this api may change, or dissapear in later pygame releases. If you use this, your code will break with the next pygame release.

You could use surface.fill() to do the job too:

def pixel(surface, color, pos):
    surface.fill(color, (pos, (1, 1)))

You can also simply draw a line with the start and end points as the same:

def pixel(surface, color, pos):
    pygame.draw.line(surface, color, pos, pos)



回答2:


For those who are interested in a more modern answer to the question you can use pygame.draw.circle() to draw a single pixel at a given position (or center).

pygame.draw.circle(surface, color, center, 0)

The documentation specifically says:

radius (int or float) -- radius of the circle, measured from the center parameter, a radius of 0 will only draw the center pixel




回答3:


draw a single coloured pixel

def drawPoint(x,y,color):

    s = pygame.Surface((1,1))   # the object surface 1 x 1 pixel (a point!)

    s.fill(color)               # color as (r,g,b); e.g. (100,20,30)

# now get an object 'rectangle' from the object surface and place it at position x,y

    r,r.x,r.y = s.get_rect(),x,y    

    screen.blit(s,r)            # link the object rectangle to the object surface

of course you have to call: pygame.display.update() once you have drawn all the points you need, don't call update at every single point.




回答4:


One way of doing that is to draw a line staring and ending at the same point.

pygame.draw.line(surface, (255,255,255), (x,y), (x,y))


来源:https://stackoverflow.com/questions/10354638/pygame-draw-single-pixel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!