[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] AACircle



Hi all, I've written an antialiased circle routine that creates a surface 2x as large as requested, blits a circle to it, then shrinks it down to size. The reason I made it is because the pygame.transform.rotozoom doesn't make a perfect looking circle.

Here it is. Any suggestions on how to make it more efficient would be appreciated. In particular, I suspect the loop that comes after the line 'Add the pixels values to a temporary array' could be made more efficient with Numeric, but I don't know Numeric well enough to know how to do that.

--Kamilche



def AACircle(radius = 10, antialias = 2, color = [255, 128, 0], width = 0):
    ' Paint a circle'
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    d = radius * 2
    r2 = radius * antialias
    d2 = r2 * 2

    # Create surface twice the size (or more)
    pic = pygame.Surface([d2, d2], 0, 8)
    pic.set_palette([[x, x, x] for x in range(256)])
    pic.fill(BLACK)

    # Draw the circle on the large picture
    pygame.draw.circle(pic, WHITE, [r2, r2], r2, width)

    # Add the pixel values to a temporary array
    array = Numeric.zeros((d, d), Numeric.Int)
    srcarray = pygame.surfarray.pixels2d(pic)
    for x in range(d2):
        for y in range(d2):
            array[x/antialias][y/antialias] += srcarray[x][y][0]
    array /= antialias * antialias

    # Create the final surface
    pic2 = pygame.Surface([d, d], pygame.SRCALPHA, 32).convert_alpha()
    pic2.fill(color)
    pygame.surfarray.pixels_alpha(pic2)[:, :] = array.astype(Numeric.UInt8)

    # Return the final surface
    return pic2