Inverting A Scale

One technique I find useful, especially when drawing images, is to invert a number on a scale. In PHP, coordinates in an image are drawn from the top left of the image. This means that if we want to draw from the bottom left then we need to invert the y coordinate.

The following is example PHP code that creates an image with a single, diagonal line, drawn across the middle.

<?php

// Set up image dimensions.
$width = 110;
$height = $width;

// Set up image.
$image = imagecreate($width, $height);

// Assign background image.
$background_color = imagecolorallocate($image, 0, 0, 0);

// Create a foreground color.
$color = imagecolorallocate($image, 255, 255, 255);

// Create a scale (0 to $width in steps of 2).
$range = range(0, $width, 2);

// Loop through the range and draw a circle at each dot.
foreach ($range as $item) {
  imagefilledellipse($image, $item, $item, 1, 1, $color);
}

// Write the image data to a file.
imagepng($image, 'line.png');

This produces the following.

Diagonal line, top left to bottom right.

Notice that the image is drawn top left to bottom right.

Now, in order to swap this so that the line goes from bottom left to top right we need to invert the numbers along the y axis. This is done by taking away the height to find the inverse of the number and then multiplying by -1 make the number positive again.

Using this formula, 25 on the y axis in an image 100 pixels high would be 75.

Using this rule we can rewrite the code to invert the line.

<?php

// Set up image dimensions.
$width = 110;
$height = $width;

// Set up image.
$image = imagecreate($width, $height);

// Assign background image.
$background_color = imagecolorallocate($image, 0, 0, 0);

// Create a foreground color.
$color = imagecolorallocate($image, 255, 255, 255);

// Create a scale (0 to $width in steps of 2).
$range = range(0, $width, 2);

// Loop through the range and draw a circle at each dot.
foreach ($range as $item) {
  imagefilledellipse($image, $item, ($item - $height) * -1, 1, 1, $color);
}

// Write the image data to a file.
imagepng($image, 'line.png');

This produces the following image, with the line running from bottom left to top right.

A line, drawn bottom left to top right

Not that we could have used the abs() function here to coerce the value into a positive integer. Multiplication, however, is much more efficient and by multiplying by -1 we don't change the value of the number, we just turn it into a positive number.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.