Jobo Fernandez
Jobo Fernandez

Reputation: 901

How do I blit a rectangular outline to a surface?

I have an obstruction tile/sprite and I want to draw a rectangular outline (32x32 or from its image rect) directly to its image surface. Ideally the colors and outline/border width will also be taken into consideration.

class Obstruction(pygame.sprite.Sprite):
    def __init__(self):
        self.image = pygame.image.load("assets/tile.png").convert_alpha()
        if s.DEBUG:
            outline = pygame.Surface((32, 32))
            self.image.blit(outline, (0, 0))

Few things I've tried:

  1. The code above generates a filled rectangle rather than an outline.
  2. The prominent answer I found online is with the use of pygame.draw.rect() but this does not blit directly to the image.
  3. I've tried creating rect1 and rect2 and did subtraction between their areas using https://www.pygame.org/wiki/SubtractRects, however the result is a Rect object which can't be blit into a Surface object.

Upvotes: 1

Views: 302

Answers (1)

Rabbid76
Rabbid76

Reputation: 211277

Draw a black rectangular outline on the image with pygame.draw.rect. The las parameter of pygame.draw.rect is optional and is the with of the line:

class Obstruction(pygame.sprite.Sprite):
    def __init__(self):
        self.image = pygame.image.load("assets/tile.png").convert_alpha()
        if s.DEBUG:
            pygame.draw.rect(self.image, "black", (0, 0, 32, 32), 1)

Upvotes: 2

Related Questions