【问题标题】:How can I use a weather icons web font in an image generated by PHP?如何在 PHP 生成的图像中使用天气图标 web 字体?
【发布时间】:2016-04-25 14:12:11
【问题描述】:

我想在动态生成的 PHP 图像中使用these icons,这样人们就可以在他们的网页上嵌入天气。

现在我正在使用met.no 的天气服务,它提供了一个名为“symbol”的简洁属性,并且是一个整数。 1 = 晴天,2 = 多云等。天气图标库上的Pull Request 包括met.no 的映射,这很酷,因为我可以调用echo "<i class='wi wi-yrno-$symbol'></i>"; 并始终获得正确的图标。

但我不知道如何使用 PHP 的图像创建功能来做到这一点。在 Javascript 中,您可以这样做:Programmatically get FontAwesome unicode value by name,但我将如何在 PHP 中做到这一点?我想我只需要创建一个 array("wi-yrno-1 => "(unicode escape code here)", "wi-yrno-2" => "(another escape code here) ... 数组,但我想知道是否有更好的方法。

【问题讨论】:

    标签: php fonts


    【解决方案1】:

    我假设您正在服务器上生成图像,然后将该内容发送到浏览器。

    您提供的 JavaScript 示例无关紧要。主要是因为字体已经加载并映射到类名。在 PHP 中,您必须重新创建此映射。将符号简单映射到十进制值就可以了。例如

    $symbols = [0 => '', 1 => ..., 2 => ..., ...];
    

    设置好映射后,您需要使用的字体文件的绝对路径。在您知道您将使用imagettftext 使用给定的 ttf 字体文件在图像上绘制文本之后。它必须是一个 ttf 字体文件(因此是函数的名称)。

    // the symbol response from the met.no request
    $symbolIntFromApi = 0;
    
    // the mapping for the decimal characters
    $symbols = [0 => ''];
    
    // create the image
    $image = imagecreatetruecolor(1000, 1000);
    
    // set background color to white
    imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255));
    
    // write the text using the given font
    imagettftext($image, 12, 0, 20, 20, 0, realpath('./font/weathericons-regular-webfont.ttf'), $symbols[$symbol]);
    
    // save the image
    imagepng($image, 'test.png');
    

    【讨论】:

    • 谢谢。我以为是这样,但有时当我在寻找我遇到的问题的答案时,我会惊讶于语言 W 可以做 X、Y 和 Z,而它们看起来像是不兼容的技术。
    猜你喜欢
    • 2019-03-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2020-09-09
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多