将轴对齐的矩形旋转90度
Rotate an axis aligned rectangle by a 90 degrees
我有一个矩形对象(sf::IntRect
),在2D平面上具有属性:left、top、width和height。我想绕点(0,0)旋转90度的倍数(即90、180或270)。因此,我正在编写这样一个函数:
void rotateRect(sf::IntRect& rect, int rot)
{
//code I need
}
旋转为0(0)、1(90)、2(180)或3(270)。
我怎样才能尽可能简单地做到这一点。
以下是在sf::FloatRect
上使用sf::Tranform
的基本解决方案:
constexpr auto rotationAngle(int rot) { return rot * 90.f; }
void rotateRect(sf::IntRect& rect, int rot)
{
auto deg = rotationAngle(rot);
auto transform = sf::Transform();
transform.rotate(deg);
// Would be better if rect was a FloatRect...
auto rectf = sf::FloatRect(rect);
rectf = transform.transformRect(rectf);
rect = static_cast<sf::IntRect>(rectf);
}
然而,我个人会稍微更改您的函数的签名,以使用float rects和更紧凑的表示法:
sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot)
{
return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect);
}
下面是一个完整的例子,展示了它的行为。
#include <SFML/Graphics.hpp>
constexpr auto rotationAngle(int rot) { return rot * 90.f; }
sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot)
{
return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect);
}
void updateShape(sf::RectangleShape& shape, sf::FloatRect const& rect)
{
shape.setPosition(rect.left, rect.top);
shape.setSize({ static_cast<float>(rect.width), static_cast<float>(rect.height) });
}
int main(int, char const**)
{
sf::RenderWindow window(sf::VideoMode(500, 500), "rotate");
auto rect = sf::FloatRect(0, 0, 100, 50);
auto shape = sf::RectangleShape();
shape.setFillColor(sf::Color::Red);
updateShape(shape, rect);
auto view = window.getView();
view.move({ -250, -250 });
window.setView(view);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::R)
{
rect = rotateRect(rect, 1);
updateShape(shape, rect);
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::N)
{
rect = sf::FloatRect(50, 50, 100, 50);
updateShape(shape, rect);
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::M)
{
rect = sf::FloatRect(0, 0, 100, 50);
updateShape(shape, rect);
}
}
window.clear();
window.draw(shape);
window.display();
}
return EXIT_SUCCESS;
}
注意:我使用了C++14中的一些技巧,但我相信如果需要的话,你可以将代码转换为C++11/C++98。
相关文章:
- 在C++中使用OpenCV矩阵中的特征将图像旋转90度
- 顺时针旋转 M*N 矩阵 90 度,C++
- 在 64 位整数内旋转(90°)位矩阵(最多 8x8 位)
- 从iPhone相机拍摄的视频似乎被OpenCV旋转了90度?我该如何解决这个问题?
- 顺时针旋转90度图像
- 有关将位图旋转 90° 的说明
- 将矩阵逆时针旋转 180 度的问题
- C++向量的向量.阵列旋转 90 度
- 在C 中旋转像素阵列90度
- 将轴对齐的矩形旋转90度
- 如何使OpenGL相机旋转360度
- 在 iOS 中将 Spirte 矩形旋转 90 度不会显示纵横比
- 将2D转换的1D阵列顺时针旋转90度
- 如何将计算机绘图旋转 90 度
- 当 x 为 90 度或 pi/2 弧度时,将 cos(x) 计算为 0,以C++为单位
- 如何用OpenCV将图像分成四个象限,并将象限1和象限4旋转180度
- 旋转NxN矩阵计数器(反)-顺时针90度
- 算法旋转任意梯度90度
- 将Opencv矩阵旋转90、180、270度
- 字节数组,我需要把它旋转 90 度