How can I color a Pygame image surface? I either want to change every pixel that is color A into color B, or else change every pixel into color B. Either works, so long as transparent regions remain the same.
Essentially what a surfarray does is directly modify the pixel values of pygame surfaces, and can operate on each of the R, G, and B channels for every pixel "simultaneously," which I put in quotes because I just mean you can change all the pixels with just one line of code. Ordinarily, this would be a very slow operation, but surfarrays use numpy/numeric as their core, so the operation is quite fast. I should still note that in practice, I've found it not to be fast enough for some applications, such as operating on large images, but if you're only operating on small particle sprites, you should be fine.
I did a bit of toying around to make sure that this works as you need it. Below is a code example of what you're looking to do. Some credit goes to the poster who answered this question.
In that function, I use
which I also left out because I've found this to be a startlingly slow call in practice. It might be necessary if you try to do more complicated things with the surface.
So, the last few steps are actually taking your original surface and coloring it the way you need:
A couple of notes about this code: the call to
This ended up rather long... One last note... If you're feeling adventurous, you can look into the gfxdraw libraries for pygame. The
Hope this helps :)