Inverting A Scale

23rd February 2020

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.

  1. <?php
  2.  
  3. // Set up image dimensions.
  4. $width = 110;
  5. $height = $width;
  6.  
  7. // Set up image.
  8. $image = imagecreate($width, $height);
  9.  
  10. // Assign background image.
  11. $background_color = imagecolorallocate($image, 0, 0, 0);
  12.  
  13. // Create a foreground color.
  14. $color = imagecolorallocate($image, 255, 255, 255);
  15.  
  16. // Create a scale (0 to $width in steps of 2).
  17. $range = range(0, $width, 2);
  18.  
  19. // Loop through the range and draw a circle at each dot.
  20. foreach ($range as $item) {
  21. imagefilledellipse($image, $item, $item, 1, 1, $color);
  22. }
  23.  
  24. // Write the image data to a file.
  25. 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.

  1. <?php
  2.  
  3. // Set up image dimensions.
  4. $width = 110;
  5. $height = $width;
  6.  
  7. // Set up image.
  8. $image = imagecreate($width, $height);
  9.  
  10. // Assign background image.
  11. $background_color = imagecolorallocate($image, 0, 0, 0);
  12.  
  13. // Create a foreground color.
  14. $color = imagecolorallocate($image, 255, 255, 255);
  15.  
  16. // Create a scale (0 to $width in steps of 2).
  17. $range = range(0, $width, 2);
  18.  
  19. // Loop through the range and draw a circle at each dot.
  20. foreach ($range as $item) {
  21. imagefilledellipse($image, $item, ($item - $height) * -1, 1, 1, $color);
  22. }
  23.  
  24. // Write the image data to a file.
  25. 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.