Monthly Archives: October 2008

Rounded polygons in PHP, using GD

A while ago someone posted a question on a PHP forum about how one could draw a polygon with rounded corners, using GD, in PHP.

It looked like an interesting challenge; so I started writing some code that would draw rounded polygons.

I would not recommend using this in production. There are better ways to do this. Use a library or call out to another language.

How it works

We consider 3 vertices, A, B and C which make a triangle. We are working in 2D, so the vector space is R^2.

To make things easier we apply some affine transformations, so that the Y axis will become the bisector of the ABC angle.

Now we know that the center of the fillet arc is on the angle’s bisector. This simplifies things a bit, because we won’t need to compute the X coordinate of the arc center; it’s 0.

We compute the fillet arc center’s Y coordinate, the arc’s start and end points and then we apply the inverse transformations.

If we do this for each vertex triple, we end up having a polygon with rounded corners.

It would also be useful to draw filled polygons, but GD’s flood fill does a lousy job (especially if the lines are antialiased); so I wrote some custom polygon filling code.

Demo (a weird star)

Live demo of PHP drawn polygon with rounded corners.

Download the PHP code

download the code (poly.tar.bz2).