问题描述
我想在图像周围绘制红色边框,但不知道如何绘制.
I'd like to draw a red border around an image, but can't figure out how.
我尝试填充 Hero
精灵的图像并将颜色键设置为红色 self.image.set_colorkey(red)
,但这会使图像不可见.
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.
在图像上绘制一个红色矩形,将其完全填充:pygame.draw.rect(self.image, red, [0, 0, width, height])
.
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.
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)
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
推荐答案
您可以将 width 参数传递给 pygame.draw.rect().
You can pass a width argument to pygame.draw.rect().
换行
pygame.draw.rect(self.image, red, [0, 0, width, height])
到
pygame.draw.rect(self.image, red, [0, 0, width, height], 1)
应该做你想要的!
我意识到这篇文章很旧,但这是我遇到的一个问题,目前的最佳答案没有帮助.我找到了这个解决方案,希望它也能帮助其他人!
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!
这篇关于如何在pygame中围绕精灵或图像绘制边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!