You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PDFlib中矩形的默认对齐锚点从左下角改为中心?

修改PDFlib矩形对齐锚点为中心的方法

PDFlib的rect()方法默认以左下角作为锚点,要实现中心对齐,无需修改API的默认设置,只需通过坐标计算调整传入的参数即可:

  • 核心逻辑:若期望矩形的中心坐标为($centerX, $centerY),则对应的左下角坐标应为($centerX - $width/2, $centerY - $height/2),将计算后的坐标传入rect()方法即可。

示例代码:

// 设定矩形中心坐标、宽高
$centerX = 300;
$centerY = 400;
$width = 100;
$height = 80;

// 计算左下角锚点坐标
$x = $centerX - $width / 2;
$y = $centerY - $height / 2;

// 绘制中心对齐的矩形
$p->rect($x, $y, $width, $height);

如果需要频繁绘制中心对齐的矩形,可以封装成工具函数简化调用:

function rectCenter($p, $centerX, $centerY, $width, $height) {
    $x = $centerX - $width / 2;
    $y = $centerY - $height / 2;
    return $p->rect($x, $y, $width, $height);
}

// 调用示例
rectCenter($p, 300, 400, 100, 80);

内容的提问来源于stack exchange,提问作者Ney LS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:52:04