当前位置: 首页 > 编程文章 >

PHP实现限定区域内自动调整字体大小的类

PHP实现限定区域内自动调整字体大小的类

作者:沈安时间:2025-02-22 17:05:20浏览:360

介绍一个名为imagefittext.class.php的PHP类,该类能够在指定的矩形区域内自动计算并调整字体大小,以确保文本完全显示且不溢出。通过具体的使用范例展示如何调用此类进行图像文字绘制,适用于需要动态生成包含不同长度文本的图片场景。

本文目录收起

PHP限定区域字体自适应类介绍

本示例详细解析了一个PHP类,其核心功能是在给定的边界范围内智能调节字体的尺寸。该方案旨在解决固定区域内容排版问题,供开发者参考借鉴。

核心组件为imagefittext.class.php文件,它专门负责处理在预设几何区域内对字体大小进行自动化适配的逻辑,确保文本内容完整呈现。


<?php
// Image Fit Text Class 0.1 by ming0070913
CLASS ImageFitText{
 public $font, $fontsize, $width, $height;
 public $step_wrap, $step_fontsize;
 public function __construct($font, $step_wrap=1, $step_fontsize=1){
  $this->font = $font;
  $this->step_wrap = $step_wrap>1?$step_wrap:1;
  $this->step_fontsize = $step_fontsize>1?$step_fontsize:1;
 }
 function fit($width, $height, $text, $fontsize, $min_fontsize=5, $min_wraplength=0){
  $this->fontsize = & $fontsize;
  $text_ = $text;
  while($this->TextHeight($text_)>$height && $fontsize>$min_fontsize)
   $fontsize -= $this->step_fontsize;
  while(($this->TextWidth($text_)>$width || $this->TextHeight($text_)>$height) && $fontsize>$min_fontsize){
   $fontsize -= $this->step_fontsize;
   $wraplength = $this->maxLen($text);
   $text_ = $text;
   while($this->TextWidth($text_)>$width && $wraplength>=$min_wraplength+$this->step_wrap){
    $wraplength -= $this->step_wrap;
    $text_ = wordwrap($text, $wraplength, "\n", true);
    //To speed up:
    if($this->TextHeight($text_)>$height) break;
    if($wraplength<=$min_wraplength) break;
    $wraplength_ = $wraplength;
    $wraplength = ceil($wraplength/($this->TextWidth($text_)/$width));
    $wraplength = $wraplength<($min_wraplength+$this->step_wrap)?($min_wraplength+$this->step_wrap):$wraplength;
   }
  }
  $this->width = $this->TextWidth($text_);
  $this->height = $this->TextHeight($text_);
  return array("fontsize"=>$fontsize, "text"=>$text_, "width"=>$this->width, "height"=>$this->height);
 }
 function maxLen($text){
  $lines = explode("\n", str_replace("\r", "", $text));
  foreach($lines as $line)
   $t[] = strlen($line);
  return max($t);
 }
 function TextWidth($text){
  $t = imagettfbbox($this->fontsize, 0, $this->font, $text);
  return $t[2]-$t[0];
 }
 function TextHeight($text){
  $t = imagettfbbox($this->fontsize, 0, $this->font, $text);
  return $t[1]-$t[7];
 }
}
?>

具体的调用方式与配置参数如下所示:


<?php
// Image Fit Text Class 0.1 by ming0070913
// Example File
include "imagefittext.class.php";
// Settings :
// The text
$text = "PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. If you are new to PHP and want to get some idea of how it works, try the introductory tutorial. After that, check out the online manual.";
// The maximun width
$width = 200;
// The maximun height
$height = 100;
// Position of the text and the box
$x1 = 50;
$y1 = 50;
// The starting font size
$fontsize = 10;
// The minimun font size. The script will stop if it cannot fit the text even with this size.
$min_fontsize = 3;
// The minimun wrap length for each line. The script will try another font size if it cannot fit the text even with this wrap length.
$min_wraplength = 0;
// The font
$font = "arial.ttf";
// The space between the box and the text. It's independent to the script which can be ignored
$padding = 3;
// If the script cannot fit the text for certain wrap length, it will try the wrap length again with the reduction in this value.
// It reduce the accuracy, but will slightly speed up the process.
$step_wrap = 1;
// If the script cannot fit the text for certain font size, it will try the the font size again with the reduction in this value.
// It reduce the accuracy, but will slightly speed up the process.
$step_fontsize = 1;
// Create a image
$im = @imagecreatetruecolor($width+$x1*2, $height+$y1*2+80) or die('Cannot Initialize new GD image stream');
// Start the timer
$time_start = microtime_float();
// The class
$imagefittext = new ImageFitText($font, $step_wrap, $step_fontsize);
// Fit the text
// It returns the result in a array with "fontsize", "text", "width", "height"
$fit = $imagefittext->fit($width-$padding*2, $height-$padding*2, $text, $fontsize, $min_fontsize, $min_wraplength);
// Stop the timer
$time = round(microtime_float()-$time_start, 3);
$white = imagecolorallocate($im, 255, 255, 255);
// Draw a box
imagerectangle($im, $x1, $y1, $x1+$width, $y1+$height, $white);
// Write the text            +8 because the text will move up originally
imagettftext($im, $fit['fontsize'], 0, $x1+$padding, $y1+$padding+8, $white, $font, $fit['text']);
// Print some info. about the text
imagestring($im, 5, $x1, $y1+$height+30, 'Fontsize : '.$fit['fontsize'], $white);
imagestring($im, 5, $x1, $y1+$height+45, 'Text Size : '.$fit['width']."x".$fit['height'], $white);
imagestring($im, 5, $x1, $y1+$height+60, 'Box Size : '.($width-$padding*2)."x".($height-$padding*2), $white);
imagestring($im, 5, $x1, $y1+$height+75, 'Time used : '.$time.'s', $white);
// Print the image
header ('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
function microtime_float(){ // Timer
 list($usec, $sec) = explode(" ", microtime());
 return ((float)$usec + (float)$sec);
}
?>

期望上述关于PHP程序设计的分享能为读者在实际开发中提供有效的帮助与思路。

上一篇
PHP cURL 选项完整分类详解

本文详细列举了 PHP cURL 扩展中所有 CURLOPT 选项的分类及用法。根据参数值类型的不同,选项被划分为布尔型、整型、字符串型、数组型、流资源型及回调函数型六大类。内容涵盖 HTTP 方法设置、代理配置、SSL 证书验证、FTP 传输控制以及自定义数据读写等核心功能,为开发者提供全面的参考指南。

下一篇
PHP实现登录搜狐广告获取广告联盟数据的方法【附demo源码】

针对搜狐广告联盟每日手动查看收益的繁琐流程,本文介绍一种基于PHP和Curl的自动化数据采集方案。由于平台存在验证码限制,该方案采用服务器端预先手动输入验证码并保存Cookie的策略,结合定时器每隔10分钟请求页面以维持登录状态,从而实现每周自动汇总收益数据的功能。

相关文章

更多
PHP按比例截取图片的实现逻辑与工具推荐

本文介绍了在PHP中利用GD库实现图片按指定比例截取的核心方法,详细解析了宽高比判断与坐标计算逻辑。同时提供了多种实用的在线图片处理工具链接,涵盖格式转换、图标生成及Base64编码等功能,辅助开发者高效完成图像预处理任务。

2025.09.08 957
PHP实现多张图片合成一张并保存的方法

本文介绍如何使用PHP将多张图片合成为一张图片。通过示例代码展示具体的实现步骤,支持在浏览器中预览合成效果,同时可将最终生成的图片文件自动保存到指定的服务器文件夹中,满足常见的图片处理需求。

2025.04.04 940
PHP使用GD库创建图像的具体步骤与格式支持

本文详细介绍如何利用PHP结合GD库创建和处理多种格式的图像,包括GIF、PNG、JPEG等。重点讲解在验证码场景下,如何通过编译GD库实现图像数据流直接输出到浏览器,并列出关键函数参考路径,帮助开发者快速掌握PHP绘图基础。

2025.03.16 858
PHP 图像绘制实例详解

本文分享一个 PHP 图像绘制的具体实现方法,包含完整的代码示例及运行效果展示。该实例演示了如何利用 PHP 进行基础的图形生成操作,为开发者提供直观的参考。更多相关函数与机制可查阅官方文档中的图像引用部分。

2026.01.13 845
PHP实现仿微信群头像合成:多张图片合并为圆形组合图

本文介绍如何使用PHP的GD库实现仿微信群头像的图片合成效果。通过自定义函数getGroupAvatar,将多张正方形图片裁剪为圆形并排列组合成一张新的圆形大图。代码包含参数验证、图像创建、坐标计算及保存输出逻辑,并提供完整的调用示例供开发者参考。

2026.11.03 755
PHP图像验证码生成示例代码

本文分享了一个使用PHP封装的图像验证码生成实例。内容包含核心代码结构说明以及实际的运行结果展示,旨在为开发者提供清晰的参考与实现思路,帮助快速集成验证码功能。

2026.10.15 745

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。