Core PHP

Antialiased Triangles with GD

This GD example program demonstrates the code for an example program that demonstrates how to draw antialiased triangles with GD and create a png image.

AntialiasedTriangles.php

<?php
	function LeftOn($dX1, $dY1, $dX2, $dY2, $dPX, $dPY) {
		return ((($dX2 - $dX1)*($dPY - $dY1) - ($dPX - $dX1)*($dY2 - $dY1)) <= 0);
	}

	// We need P3 to be left of the P1 P2 line segment.
	function SmoothTriangle(&$qrImage, $dX1, $dY1, $dX2, $dY2, $dX3, $dY3, $qColor) {
		$iWidth = ImageSX($qrImage);
		$iHeight = ImageSY($qrImage);
		for ($i = 0; $i < $iWidth; ++$i) {
			for ($j = 0; $j < $iHeight; ++$j) {
				// Filter indices
				// Locations: -.4, -.2, 0, .2, .4
				$iWeight = 0;
				for ($iXF = 0; $iXF < 5; ++$iXF) {
					for ($iYF = 0; $iYF < 5; ++$iYF) {
						$dX = $i + .2*$iXF - .4;
						$dY = $j + .2*$iYF - .4;
						$bLeftOn1 = LeftOn($dX1, $dY1, $dX2, $dY2, $dX, $dY);
						$bLeftOn2 = LeftOn($dX2, $dY2, $dX3, $dY3, $dX, $dY);
						$bLeftOn3 = LeftOn($dX3, $dY3, $dX1, $dY1, $dX, $dY);
						if ($bLeftOn1 && $bLeftOn2 && $bLeftOn3) {
							$iWeight += 1;
						}
					}
				}
				// Get the current pixel index
				if ($iWeight != 0) {
					// reweight using a semicircle to approximate logarithmic response
					// Use a semicircle response curve x/w = y^2/w^2 --> y = sqrt(w*x)/w
					// The maximum weight is 25.
					$qPixel = ImageColorExactAlpha( $qrImage,
						$qColor[ 'R' ], $qColor[ 'G' ], $qColor[ 'B' ],
						( 127 - 127*sqrt(25*$iWeight)/25 ) );
					ImageSetPixel( $qrImage, $i, $j, $qPixel);
				}
			}
		}
	}

    $qImage = ImageCreateTrueColor( 320, 240 );

	// These triangles must be positively oriented.
    SmoothTriangle($qImage, 20, 20, 160, 200, 300, 120,
    	Array( 'R' => 0x40, 'G' => 0x80, 'B' => 0x40 ));
    SmoothTriangle($qImage, 10, 120, 300, 50, 120, 20,
    	Array( 'R' => 0x80, 'G' => 0x80, 'B' => 0xF0 ));

    Header('Content-Type: image/png');
    ImagePNG($qImage);
    ImageDestroy($qImage);
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.