1

I am trying to create a pixel-art making program using pygame (yes, I know there are better packages to use). The way that I am drawing pixels is via surface.set_at(). I need to know how to completely delete a pixel from a pygame surface, so that I can have an eraser tool. I do not want to fill the pixel in with the background color of the window, because that would still render when using pygame.image.save() to get an image file from the drawing. Can someone please help? Here is my code:

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)
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

As discussed in the comments, you can make a pixel transparent by setting it to a value whose alpha value is zero.

                            #r #g #b #a
canvas_surf.set_at((x, y), (0, 0, 0, 0))
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thank you! I didn't realize that the alpha value was set inside the color value! I previously tried putting the alpha value as a separate argument in the set_at() function. Thanks for the help! – hotwheel2007 Jan 02 '22 at 20:40