How do I blit a rectangular outline to a surface?

Question:

I have an obstruction tile/sprite and I want to draw a rectangular outline (32×32 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.
Asked By: Jobo Fernandez

||

Answers:

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)
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.