Skip to content

Instantly share code, notes, and snippets.

@duncanjbrown
Created June 15, 2012 08:41
Show Gist options
  • Save duncanjbrown/2935461 to your computer and use it in GitHub Desktop.
Save duncanjbrown/2935461 to your computer and use it in GitHub Desktop.
Adjust text tracking with PHP/FreeType
<?php
/**
* This is based on the work of ryan at retronetworks dot com
* Who posted the original function on the PHP manual.
* I had occasion to find the pixel width of the created string so now
* a) the function returns the length
* and b) there's a stripped-down imagettfbbox which does the same thing
*
* Ryan's original code: http://www.php.net/manual/en/function.imagettfbbox.php#51373
*/
/**
* Get the length of a FreeType text string with specified tracking. Does not write into an image.
*
* @param the same as imagettfbbox() with an extra $tracking variable in pixels
*
* @return the width of the created string
*/
function imagettfbbox_width_with_tracking( $size, $angle, $fontfile, $text, $tracking ) {
$numchar = strlen($text);
$w = 0;
for($i = 0; $i < $numchar; $i++) {
$char[$i] = substr($text, $i, 1);
$char_dimensions = imagettfbbox( $size, $angle, $fontfile, $char[$i] );
$w += $char_dimensions[2];
}
return $w + ( $numchar * $tracking );
}
/**
* Use FreeType to write a text string into an image
*
* @param the same as imagettftext() with an extra $tracking variable in pixels
*
* @return the width of the created string
*/
function imagettftext_with_tracking( $im, $size, $angle, $x, $y, $color, $font, $text, $tracking ) {
$numchar = strlen($text);
$w = 0;
$characters_width = 0;
for($i = 0; $i < $numchar; $i++) {
$char[$i] = substr($text, $i, 1);
imagettftext($im, $size, $angle, ($x + $w + ($i * $tracking) ), $y, $color, $font, $char[$i]);
$char_dimensions = imagettfbbox($size, $angle, $font, $char[$i]);
$characters_width += $char_dimensions[2];
$w = $w + $char_dimensions[2];
}
return $characters_width + ( $numchar * $tracking );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment