【问题标题】:Deleting a Pixel From a Pygame Surface从 Pygame 表面删除像素
【发布时间】:2022-01-02 20:14:00
【问题描述】:

我正在尝试使用 pygame 创建一个像素艺术制作程序(是的,我知道有更好的软件包可供使用)。我绘制像素的方式是通过surface.set_at()。我需要知道如何从 pygame 表面上完全删除一个像素,这样我才能拥有一个橡皮擦工具。我不想用窗口的背景颜色填充像素,因为当使用 pygame.image.save() 从绘图中获取图像文件时,它仍然会呈现。有人可以帮忙吗?这是我的代码:

import pygame
import sys
import math

pygame.init()
clock = pygame.time.Clock()

pygame.display.set_caption("Pixel Studio v1.1")
screen = pygame.display.set_mode((960, 720), pygame.RESIZABLE)

scroll_speed = 5
canvas_size = (32, 16)
color = (255, 255, 255)

canvas_surf = pygame.Surface(canvas_size, pygame.SRCALPHA)

zoom = 12
mouse_down = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.image.save(canvas_surf, "canvas.png")
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == pygame.BUTTON_LEFT:
                mouse_down = True
            if event.button == pygame.BUTTON_WHEELUP:
                if zoom > 2:
                    zoom -= scroll_speed
            if event.button == pygame.BUTTON_WHEELDOWN:
                    zoom += scroll_speed
        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == pygame.BUTTON_LEFT:
                mouse_down = False

    if zoom < 2:
        zoom = 2

    screen.fill((50, 50, 50))
    #canvas_surf.fill((200, 200, 200))

    canvas_surf_scaled = pygame.transform.scale(canvas_surf,(canvas_surf.get_width() * zoom, canvas_surf.get_height() * zoom))
    canvas_rect = canvas_surf_scaled.get_rect(center=(screen.get_width()/2, screen.get_height()/2))

    mouse_pos = pygame.mouse.get_pos()

    if mouse_down:
        canvas_surf.set_at((math.floor((mouse_pos[0] - canvas_rect.x) / zoom), math.floor((mouse_pos[1] - canvas_rect.y) / zoom)), color)

    pygame.draw.rect(screen, ( 75, 75, 75), canvas_rect, 1,)
    screen.blit(canvas_surf_scaled, canvas_rect)

    pygame.display.flip()
    clock.tick(60)

【问题讨论】:

    标签: python pygame pygame-surface


    【解决方案1】:

    如 cmets 中所述,您可以通过将像素设置为 alpha 值为 0 的值来使像素透明。

                                #r #g #b #a
    canvas_surf.set_at((x, y), (0, 0, 0, 0))
    

    【讨论】:

    • 谢谢!我没有意识到 alpha 值是在颜色值中设置的!我之前尝试将 alpha 值作为单独的参数放在 set_at() 函数中。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多