|
Drawing Lines At last, we’re finally getting into the art! Starting with
lines, let’s examine the function we will be using:
imageline ( [image] , [x1] , [y1] , [x2] , [y2] , [color] )
Our function imageline() accepts 6 arguments: the image identifier, the x
and y coordinates of the starting point for the line, the x and y coordinates
for the end point of the line and the colour identifier for the line (a variable
containing a call to imagecolorallocate() or similar).
You don’t call this function from within a variable, you simply call it, so
let’s try drawing a red line from 0,0 to 150,150 on an image:
<?php
$im = imagecreate(150, 150);
$bg = imagecolorallocate($im, 255, 255, 255);
# let’s just use a white background.
$red = imagecolorallocate($im, 255, 0, 0);
# our red colour defined for the line
imageline($im, 0, 0, 150, 150, $red);
# output here, we will cover this later
?>
|
And it’s done! Once the output functions have been put in,
you will have a white 150px square image with a red line from the top left
corner to the bottom right. It should look something like this:

Drawing Polygons The functions for drawing shapes are essentially
simple to understand. The function we use to draw a polygon is called
imagepolygon(). It accepts 4 arguments: the image identifier, an array
containing each point’s x and y coordinate, the number of points in total and
the colour.
For the following example, I’ll make it easier by using the array function count() to
define the number of points for you, so all you will have to do is add new
points to the array. This example will create a 400x400px canvas and draw a triangle on it:
<?php
$im = imagecreate(400, 400);
$bg = imagecolorallocate($im, 0, 0, 0);
# simple white background
$red = imagecolorallocate($im, 255, 0, 0);
$points = array(
200, 50,
50, 300,
350, 300
);
$num = count($points) / 2;
# num now = 3
imagepolygon($im, $points, $num, $red);
# triangle drawn
# output image
?>
|
And that's how we draw a triangle on a black canvas. After you
have done this, and put in the outputting code, your image should look
something like this:

A neat trick to try when using the imagepolygon() function is to define random
points using mt_rand() instead of defining points. This can produce a cool
effect, similar to this:

The above code is the same as the example above, except with the $points array
defined like this:
$points = array(
mt_rand(50,350), mt_rand(10,80),
mt_rand(10,100), mt_rand(200,390),
mt_rand(250,390), mt_rand(200,390)
);
|
You can put any point into the mt_rand() function,
but I put some coordinates that will limit the randomness to the general
area that I want the coordinate to make it look remotely like the
first example. Feel free to use this code in your work, I have used
random coordinates in imagepolygon() for a signature image or two... ;)
Now that's progression! Let’s go on to drawing rectangles (somewhat easier).
- Tutorial written by Scrowler
|