php-gdlabel/src/Elements/TextElement.php

72 lines
1.8 KiB
PHP

<?php
namespace NoccyLabs\GdLabel\Elements;
use NoccyLabs\GdLabel\Element;
class TextElement extends Element
{
private static $fontCache = [];
private static function findFont($font)
{
if (count(self::$fontCache)==0) {
self::updateFonts();
}
$font = strtolower($font);
if (array_key_exists($font, self::$fontCache)) {
return self::$fontCache[$font];
}
return false;
}
private static function updateFonts()
{
exec("fc-list", $output, $ret);
if ($ret != 0) {
fprintf(STDERR, "%s\n", join("\n",$output));
return;
}
foreach ($output as $line) {
$seg = explode(":", $line);
$file = $seg[0];
$name = strtolower(trim(preg_replace("/[^A-Za-z0-9 ]/", '', $seg[1])));
self::$fontCache[$name] = $file;
}
}
protected function draw($gd, int $x, int $y, int $width, int $height, array $params)
{
if (($bound = $this->getProp("bind-value"))) {
$value = array_key_exists($bound, $params)?$params[$bound]:"?{$bound}?";
} else {
$value = $this->getProp("value");
}
$font = self::findFont("liberation sans");
if (!$font) {
return;
}
$color = $this->getPropRgb("text-color");
$size = $this->getProp("font-size", 8);
$dims = imagettfbbox($size, 0, $font, $value);
$textAscent = abs($dims[7]);
$textDescent = abs($dims[1]);
$textWidth = abs($dims[0])+abs($dims[2]);
$textHeight = $textAscent+$textDescent;
imagettftext($gd, $size, 0, $x, $y + $textAscent, $color, $font, $value);
//imagestring($gd, $size, $x, $y, $value, $color);
}
}