Is there any easy way to create an angled rectangle in php?

802 views Asked by At

I wonder if there is rather an easy way to draw an angled rectangle using GD in php?
I know I can use the imagefilledpolygon function but that's a bit tricky considering you should calculate all the points manually.

I think a reformed version of imagefilledrectangle would be like this:

imagefilledrectangle($img,$centerX,$centerY,$angle,$color);

Where $centerX and $centerY would be coordinates of the rectangles center point.
or anything similar to that.

1

There are 1 answers

1
Hammerite On

What do you mean by "angled rectangle"? You mean a rectangle whose sides aren't perpendicular to the x- and y-directions of the image?

To use the imagefilledrectangle() function you have to supply the co-ordinates of two points that define the extent of the rectangle. I would have thought that if you want to draw a rectangle that's rotated through an angle then you probably want to provide

  • the width and height of the rectangle
  • the centre of the rectangle (or another specified point, like a distinguished vertex of the rectangle)
  • the angle through which the rectangle is to be rotated.
You mention each of these except the width and height.

Suppose I wanted to make a function imagefilledrotatedrectangle($img, $centerX, $centerY, $width, $height, $angle, $color). I would probably have it compute the 4 vertices of the rectangle, and then make a call to imagefilledpolygon() passing in those 4 points. In pseudocode:

(Let's assume that my vertices are labelled 1, 2, 3 and 4, going around clockwise. I can represent them as pairs of integers, getting me integers $x1, $y1, $x2, $y2, $x3, $y3, $x4 and $y4.)

function imagefilledrotatedrectangle( $img,
                                      $centerX, $centerY,
                                      $width, $height,
                                      $angle,
                                      $color
                                      ) {
    // First calculate $x1 and $y1. You may want to apply
    // round() to the results of the calculations.
    $x1 = (-$width  * cos($angle) / 2) + $centerX;
    $y1 = (-$height * sin($angle) / 2) + $centerY;
    // Then calculate $x2, $y2, $x4 and $y4 using similar formulae. (Not shown)
    // To calculate $x3 and $y3, you can use similar formulae again, *or*
    // if you are using round() to obtain integer points, you should probably
    // calculate the vectors ($x1, $y1) -> ($x2, $y2) and ($x1, $y1) -> ($x3, $y3)
    // and add them both to ($x1, $y1) (so that you do not occasionally obtain
    // a wonky rectangle as a result of rounding error). (Not shown)
    imagefilledpolygon( $img,
                        array($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4),
                        4,
                        $color
                        );
}