PDFlib - 以任意度数围绕中心旋转对象

PDFlib - rotating objects around center by arbitrary degree

任务: 我需要将一个正方形、长方形或三角形围绕其中心点旋转任意角度。

PDFlib 文档声明旋转总是围绕对象的 左下角 角发生。

这是我尝试围绕其中心旋转一个正方形:

// Gray square positioned before rotation
$p->setcolor('stroke', '#999999', null, null, null, null);
$p->rect(200, 200, 100, 100);
$p->stroke();

// Red square rotated by 45 degrees, around its center as pivot
$p->setcolor('stroke', '#ff0000', null, null, null, null);
$p->save();
$p->translate(200 - 20.71, 200 - 50); // 20.71 is the calculation product
$p->rotate(360 - 45);
$p->rect(0, 0, 100, 100);
$p->stroke();
$p->restore();

结果:

这很简单。

但是,我需要能够将矩形绕其中心旋转任意度数。几何会很快让事情变得复杂 :-)

问题:PDFlib 是否支持任何对象围绕其中心旋转任意度数

好吧,PDFlib 不会为您计算几何。下面是计算旋转矩形偏移量的代码:

$x = 10;
$y = 10;
$width = 80;
$height = 40;
$angle = -33;
$centerX = $width / 2;
$centerY = $height / 2;
// Diagonal angle
$diagRadians = atan($width / $height);
$diagAngle = rad2deg($diagRadians);
// Half Length diagonal
$diagHalfLength = sqrt(pow($height, 2) + pow($width, 2)) / 2;

// Center coordinates of rotated rectangle.
$rotatedCenterX = sin($diagRadians + deg2rad($angle)) * $diagHalfLength;
$rotatedCenterY = cos($diagRadians + deg2rad($angle)) * $diagHalfLength;

$offsetX = $centerX - $rotatedCenterX;
$offsetY = $centerY - $rotatedCenterY;

$p->setcolor('stroke', '#ff00ff', null, null, null, null);
$p->save();
$x += $offsetX;
$y -= $offsetY;
$p->translate($x, $y);
// Place a dot at rotated rectangle center
$p->circle($rotatedCenterX, $rotatedCenterY * -1, 5); 
$p->stroke();
$p->rotate(360 - $angle);
$p->rect(0, 0, $width, $height);
$p->stroke();
$p->restore();