I am drawing a series of polygons using imagepolygon and would like to place a single letter label at the center (or somewhere inside) of the polygon. Is there a function or algorithm available to do this? It needs to work with irregular polygons as well.

    Well... in theory, you should have a series of point to draw your pollygon. You would have to find 4 couples :

    -> the X nearest the left... P1: (x1, y1)
    -> the X nearest the right... P2: (x2, y2)
    -> the Y nearest the top... P3: (x3, y3)
    -> the Y nearest the bottom... P4: (x4, y4)

    To find the center :

    Pc: (round((x2 - x1) / 2), round((y4 - x3) / 2))

      This would not work for many irregular polygons. For example, think of an L-shaped polygon. The center is outside the polygon.

        Not perfect, but may help :-

        If you have a convex polygon then the above algorithm works.

        Test if you do have a convex polygon by

        fill polgon with a colour not used anywhere else in image
        take each vertex n and vertex n+2 and calculate midpoint
        if '[man]imagecolorat[/man]' each midpoint is the polygon colour then polygon is convex and above algorithm can be applied

        if concave
        take a vertex n
        test midpoints of vertex n and vertex n+y (y >= 2) incrementing y until colour at midpoint is the polygon colour
        Place your letter at that midpoint

          Write a Reply...