Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a border around a sprite or image in pygame?

I'd like to draw a red border around an image, but can't figure out how.

I've tried to fill the image of the Hero sprite and set the colorkey to red self.image.set_colorkey(red), but that makes the image invisible.

Drawing a red rect onto the image, just filled it completely: pygame.draw.rect(self.image, red, [0, 0, width, height]).

I just want a red border that will help with collision detection in the future.

The code in main.py:

import pygame
from pygame import *
import sprites
from sprites import *
pygame.init()

width = 640
height = 480
color = (255, 255, 255) #white
x = 0
y = 0
speed = 3

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Mushroom")
icon = pygame.image.load('icon.bmp')
pygame.display.set_icon(icon)
sprites_list = pygame.sprite.Group()

hero = Hero('mushroom.png', 48, 48)
hero.rect.x = 200;
hero.rect.y = 300;

sprites_list.add(hero)

running = True
clock = pygame.time.Clock()
while running:
    sprites_list.update()
    screen.fill((color))
    sprites_list.draw(screen)
    hero.draw(screen)
    pygame.display.flip()
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
       hero.left(speed)
    if key[pygame.K_RIGHT]:
       hero.right(speed)
    if key[pygame.K_UP]:
       hero.up(speed)
    if key[pygame.K_DOWN]:
       hero.down(speed)

    clock.tick(60)

The code in sprites.py:

import pygame
from pygame import *

red = (255, 0, 0)

class Hero(pygame.sprite.Sprite):
    def __init__(self, color, width, height):

        super().__init__()

        self.image = pygame.image.load('mushroom.png')
        self.image = pygame.Surface((width, height))
        self.image.fill(red)
        self.image.set_colorkey(red)

        pygame.draw.rect(self.image, red, [0, 0, width, height])
        self.rect = self.image.get_rect()

    def draw(self, screen):
        screen.blit(self.image, self.rect)

    def right(self, pixels):
        self.rect.x += pixels
    def left(self, pixels):
        self.rect.x -= pixels
    def up(self, pixels):
        self.rect.y -= pixels
    def down(self, pixels):
        self.rect.y += pixels
like image 866
Yeoha I Avatar asked Oct 29 '22 00:10

Yeoha I


1 Answers

You can pass a width argument to pygame.draw.rect().

Changing the line

pygame.draw.rect(self.image, red, [0, 0, width, height])

to

pygame.draw.rect(self.image, red, [0, 0, width, height], 1)

should do what you're looking for!

EDIT: I realize this post is old, but this was an issue I was having, and the current top answer didn't help. I found this solution, and hope it can help others too!

like image 148
MTurek Avatar answered Nov 15 '22 05:11

MTurek