php-gdlabel/src/Elements/TextElement.php

89 lines
2.3 KiB
PHP

<?php
namespace NoccyLabs\GdLabel\Elements;
use NoccyLabs\GdLabel\Element;
class TextElement extends Element
{
private static $fontCache = [];
private static function findFont($font, $style='regular')
{
if (count(self::$fontCache)==0) {
self::updateFonts();
}
$font = strtolower($font);
if (array_key_exists($font, self::$fontCache)) {
$info = self::$fontCache[$font];
if (!$style) {
return $info;
}
if (array_key_exists($style, $info)) {
return $info[$style];
}
return false;
}
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])));
$style = strtolower(str_replace("style=","",$seg[2]));
$style = explode(",",$style);
$style = reset($style);
if (!array_key_exists($name, self::$fontCache)) {
self::$fontCache[$name] = [];
}
self::$fontCache[$name][$style] = $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");
}
$fontName = $this->getProp("font")?:"liberation sans";
$font = self::findFont($fontName);
if (!$font) {
return;
}
$color = $this->getPropRgb("text-color");
$size = $this->getProp("font-size", 8);
$dims = imagettfbbox($size, 0, $font, "AaBbXxYyZz0129:;.");
$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);
}
}