我使用Python和pygame来制作一个简单的绘图应用程序。
我需要一种方法来复制区域中的像素(例如,从X 100,Y 100到X 200,Y 200),保存,然后再将其放下。就像截图一样。
也许表面......?
我不知道表面是如何工作的,甚至不知道他们做了什么。
答案 0 :(得分:1)
您可以使用Surface.subsurface
来创建地下。
这是一个简单的例子。用鼠标选择一个区域,然后再次按下鼠标按钮,对所选的子表面进行blit:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
for x in xrange(0, 800):
pygame.draw.rect(screen, ((x+100)%255, (x*2)%255, x%255), pygame.Rect(x, 0, 1, 800))
org_screen = screen.copy()
class Cursor(object):
def __init__(self):
self._inner = CopyCursor()
def mousedown(self, mpos):
self._inner = self._inner.mousedown(mpos)
def mouseup(self, mpos):
self._inner = self._inner.mouseup(mpos)
def draw(self, screen, mpos):
self._inner.draw(screen, mpos)
class CopyCursor(object):
def __init__(self):
self.start, self.end = None, None
def mousedown(self, mpos):
self.start = mpos
return self
def mouseup(self, mpos):
if self.start and self.end:
r = pygame.Rect(self.start, self.end)
r.normalize()
# important to call .copy() so 'sub_surf'
# loses its relation to 'screen'
return BlitCursor(screen.subsurface(r).copy())
return self
def draw(self, screen, mpos):
if self.start:
self.end = mpos[0]-self.start[0], mpos[1]-self.start[1]
rect = pygame.Rect(self.start, self.end)
pygame.draw.rect(screen, pygame.Color('grey'), rect, 3)
class BlitCursor(object):
def __init__(self, sub_surf):
self.sub_surf = sub_surf
def mousedown(self, mpos):
pygame.event.post(pygame.event.Event(pygame.USEREVENT, surface=self.sub_surf, pos=mpos))
return CopyCursor()
def mouseup(self, mpos):
pass
def draw(self, screen, mpos):
screen.blit(self.sub_surf, mpos)
cursor = Cursor()
while True:
mpos = pygame.mouse.get_pos()
for e in pygame.event.get():
if e.type == pygame.QUIT: break
if e.type == pygame.MOUSEBUTTONUP: cursor.mouseup(mpos)
if e.type == pygame.MOUSEBUTTONDOWN: cursor.mousedown(mpos)
if e.type == pygame.USEREVENT:
org_screen.blit(e.surface, e.pos)
screen.blit(org_screen, (0, 0))
else:
if not pygame.event.peek(pygame.USEREVENT):
cursor.draw(screen, mpos)
pygame.display.flip()
screen.blit(org_screen, (0, 0))
clock.tick(50)
continue
break
另一种方法是在blitting时使用area
关键字,只显示源Surface
的特定区域。
第三种方法是使用pygame.transform.chop
,但这相当麻烦。