代码之家  ›  专栏  ›  技术社区  ›  Jacob Simerly

无法在pygame中的透明表面上提取

  •  1
  • Jacob Simerly  · 技术社区  · 2 年前

    我正在尝试创建一种方法,从本质上擦除曲面上的图形。我有处理包含png的曲面的功能,但当我使用相同的方法删除由绘制的曲面时 pygame.draw.lines() 它不是擦除。

    这两个表面之间的主要区别是一个是透明的,另一个不是。我想我可能不完全理解pygames透明表面是如何工作的。

    不工作 undraw() :

    class MovementComponent(AbstactComponent):
        def __init__(self) -> None:
            super().__init__()
            game_surfaces = GameSurfaces() #singleton class that rerenders all of the surfaces in order
            self.movement_surface = game_surfaces.movement_surface
            self.path_surface = pg.Surface(self.movement_surface.get_size(), pg.SRCALPHA)
            self.path_surface.set_alpha(150)
    
        def draw_movement(self):
            if len(self.queue()) >= 2:
                tile_centers = []
                for tile in self.queue():
                    tile_centers.append(tile.center_pixel)
    
                pg.draw.lines(
                    self.path_surface, 
                    self.character.color, 
                    False, tile_centers, 3
                )
                
                self.movement_surface.blit(self.path_surface, (0,0))
    
        def undraw_movement(self):
            empty = pg.Color(0,0,0,0)
            self.path_surface.fill(empty)
            self.movement_surface.blit(self.path_surface, (0,0))
    

    另一构件的工作未排水量:

    class SpriteComponent(AbstactComponent):
        NORMAL_SIZE = (55,55)
    
        def __init__(self, image: pg.image):
            surfaces = GameSurfaces()
            self.char_surface = surfaces.character_surface
            self.pixel_pos: (int,int) = None
    
            self.standard_image = pg.transform.scale(image, self.NORMAL_SIZE)
            self.empty = pg.Color(0,0,0,0)
    
        def draw(self, pixel_pos: (int, int)):
            self.pixel_pos = pixel_pos
            top_left_pixel = self.get_topleft_pos(pixel_pos)
            self.char_surface.blit(self.standard_image, top_left_pixel)
    
        def undraw(self, pixel_pos: (int, int)=None):
            pixel_pos = pixel_pos if pixel_pos else self.pixel_pos
            top_left_pixel = self.get_topleft_pos(self.pixel_pos)
            rect_to_clear = pg.Rect(top_left_pixel, self.NORMAL_SIZE)
            self.char_surface.fill(self.empty, rect_to_clear)
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Rabbid76    2 年前

    透明的 Surface 与背景混合。但是,在删除时,需要完全覆盖背景。因此,您必须 表面 暂时不透明的再次删除。如果你打电话 set_alpha 与论点 None ,之前设置的透明度将再次取消:

    class MovementComponent(AbstactComponent):
        # [...]
    
        def undraw_movement(self):
            empty = pg.Color(0,0,0,0)
            self.path_surface.fill(empty)
            self.path_surface.set_alpha(None)
            self.movement_surface.blit(self.path_surface, (0,0))
            self.path_surface.set_alpha(150)