Search code examples
phpdrawingtransparencygd

PHP GD draw shape over another shape and make it transparent


I am working on a charting library, and i use GD to draw the charts and gauges. This all works great, but i would like to have the possibility of a transparent background. I finally got that working, but now i come across a new question.

To draw complex gauges, i draw multiple shapes over each other. Like when i need a donut pie chart, i draw a regular pie chart - and then i draw a center ellipse, giving the impression of being a donut. This works great when there is a background color like white, or any other color. When using a transparent background, this draws the pie and everything as it should - i draw the donut center, but i cant turn the center to transparent.

Pie Chart: Pie Chart

Donut Chart: Donut Chart

I cant get the center (white) to be transparent, i dont want to draw the center with alpha transparency as the pie would shine through - but i want to replace the white with transparent pixels.

I tried imagecolortransparent($image, $white); but cant get it to work. Anyone that can point me in the right direction, or possibly can tell me if it is possible at all.


Solution

  • I got it working, might come in handy for other people having the same issue. I draw the center with a solid color, and then do a imagefill at the center of the shape. I fill this with a truecolor with alpha transparency set to 127. This replaces the (in my case white) pixels with pixels set to full transparency.

    Pie Radial Pie

    At the creation i use imagecreatetruecolor and i set imagesavealpha($image, true). I dont set imagealphablending($image, false) because it will cause other colors with Alpha to completely remove the background (like indicators in the donut in the question).