执行此操作的一种方法是计算旋转图像的最小边界矩形并创建具有这些尺寸的新像素图,您可以在其上渲染现在保证适合的旋转图像。为此,您可以获取图像矩形的每个角点并围绕中心旋转它们。然后,通过查看每个点并找到最小和最大 x 和 y 值,可以使用生成的点来计算最小边界矩形。
例如,在下面的假设示例中,我们有一个 100x100 的矩形。如果我们使用一个简单的算法将矩形的每个角点围绕中心旋转我们的角度(在本例中为 45 度),我们会得到四个新角点 (50, -20), (-20, 50), (120 , 120) 和 (50, 120)。从这些点我们可以看出最小x值为-20,最小y值为-20,最大x值为120,最大y值为120,所以最小bounding rect可以用topLeft来描述:(-20 , -20) 和 bottomRight:(120, 120)。
为了帮助您,这里有一个函数取自另一个 stackoverflow 帖子,用于围绕另一个点旋转一个点:
QPointF getRotatedPoint( QPointF p, QPointF center, qreal angleRads )
{
qreal x = p.x();
qreal y = p.y();
float s = qSin( angleRads );
float c = qCos( angleRads );
// translate point back to origin:
x -= center.x();
y -= center.y();
// rotate point
float xnew = x * c - y * s;
float ynew = x * s + y * c;
// translate point back:
x = xnew + center.x();
y = ynew + center.y();
return QPointF( x, y );
}
这是我编写的一个函数,它使用它来计算旋转某个角度的某个矩形的最小边界矩形...
QRectF getMinimumBoundingRect( QRect r, qreal angleRads )
{
QPointF topLeft = getRotatedPoint( r.topLeft(), r.center(), angleRads );
QPointF bottomRight = getRotatedPoint( r.bottomRight(), r.center(), angleRads );
QPointF topRight = getRotatedPoint( r.topRight(), r.center(), angleRads );
QPointF bottomLeft = getRotatedPoint( r.bottomLeft(), r.center(), angleRads );
// getMin and getMax just return the min / max of their arguments
qreal minX = getMin( topLeft.x(), bottomRight.x(), topRight.x(), bottomLeft.x() );
qreal minY = getMin( topLeft.y(), bottomRight.y(), topRight.y(), bottomLeft.y() );
qreal maxX = getMax( topLeft.x(), bottomRight.x(), topRight.x(), bottomLeft.x() );
qreal maxY = getMax( topLeft.y(), bottomRight.y(), topRight.y(), bottomLeft.y() );
return QRectF( QPointF( minX, minY ), QPointF( maxX, maxY ) );
}
所以现在我们有了旋转图像的最小边界矩形,我们可以创建一个具有宽度和高度的新像素图,并将旋转后的图像渲染到它的中心。这很棘手,因为涉及的转换使得您的源和目标矩形可能是什么变得更加混乱。它实际上并不像看起来那么难。您执行平移/旋转以围绕中心旋转绘图设备,然后您可以简单地将源图像渲染到目标图像上,就像将源图像渲染到目标中心时一样。
例如:
QPixmap originalPixmap; // Load this from somewhere
QRectF minimumBoundingRect = getMinimumBoundingRect( originalPixmap.rect(), angleRads);
QPixmap rotatedPixmap( minimumBoundingRect.width(), minimumBoundingRect.height() );
QPainter p( &rotatedPixmap );
p.save();
// Rotate the rotated pixmap paint device around the center...
p.translate( 0.5 * rotatedPixmap.width(), 0.5 * rotatedPixmap.height() );
p.rotate( angleDegrees );
p.translate( -0.5 * rotatedPixmap.width(), -0.5 * rotatedPixmap.height() );
// The render rectangle is simply the originalPixmap rectangle as it would be if placed at the center of the rotatedPixmap rectangle...
QRectF renderRect( 0.5 * rotatedRect.width() - 0.5 * originalPixmap.width(),
0.5 * rotatedRect.height() - 0.5 * originalPixmap.height(),
originalPixmap.width(),
originalPixmap.height() );
p.drawPixmap( renderRect, originalPixmap, originalPixmap.rect() );
p.restore();
瞧,一个很好的旋转图像,没有切掉任何角落。