Skip to content

Commit c615a63

Browse files
authored
Replace numpy for gradient fill (#274, #356)
2 parents 748dc41 + 381c06a commit c615a63

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

src/pgzero/screen.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import numpy as np
21
import pygame
32
import pygame.draw
43

@@ -113,6 +112,29 @@ def textbox(self, *args, **kwargs):
113112
ptext.drawbox(*args, surf=self._surf, **kwargs)
114113

115114

115+
def blit_gradient(start, stop, dest_surface):
116+
"""Blit a gradient into a destination surface.
117+
118+
The function does not return anything as the gradient is written
119+
in-place in the destination surface.
120+
121+
Args:
122+
start: The starting (top) color as a tuple (red, green, blue).
123+
stop: The stopping (bottom) color as a tuple (red, green, blue).
124+
dest_surface: A pygame.Surface to write the gradient into.
125+
Returns:
126+
None."""
127+
surface_compact = pygame.Surface((2, 2))
128+
pixelarray = pygame.PixelArray(surface_compact)
129+
pixelarray[0][0] = start
130+
pixelarray[0][1] = stop
131+
pixelarray[1][0] = start
132+
pixelarray[1][1] = stop
133+
pygame.transform.smoothscale(surface_compact,
134+
pygame.PixelArray(dest_surface).shape,
135+
dest_surface=dest_surface)
136+
137+
116138
class Screen:
117139
"""Interface to the screen."""
118140
def _set_surface(self, surface):
@@ -132,13 +154,7 @@ def fill(self, color, gcolor=None):
132154
if gcolor:
133155
start = make_color(color)
134156
stop = make_color(gcolor)
135-
pixs = pygame.surfarray.pixels3d(self.surface)
136-
h = self.height
137-
138-
gradient = np.dstack(
139-
[np.linspace(a, b, h) for a, b in zip(start, stop)][:3]
140-
)
141-
pixs[...] = gradient
157+
blit_gradient(start, stop, self.surface)
142158
else:
143159
self.surface.fill(make_color(color))
144160

0 commit comments

Comments
 (0)