PDFlib-将对象绕中心旋转任意角度

时间:2019-08-18 01:05:35

标签: pdflib

任务:我需要围绕正方形,矩形或三角形的中心旋转任意角度。

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();

结果

square rotation

那很简单。

但是,我需要能够围绕矩形的中心任意旋转矩形。几何使事情变得复杂:-)

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

1 个答案:

答案 0 :(得分:0)

好吧,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();