帮我用C++写二维图形的平移、旋转和缩放,根据输入的参数实现变化
时间: 2024-02-28 11:53:14 浏览: 17
好的,我可以帮你实现二维图形的平移、旋转和缩放。以下是C++代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 定义二维向量结构体
struct Vector2 {
float x, y;
Vector2() : x(0), y(0) {}
Vector2(float x, float y) : x(x), y(y) {}
Vector2 operator+(const Vector2& v) const { return Vector2(x + v.x, y + v.y); }
Vector2 operator-(const Vector2& v) const { return Vector2(x - v.x, y - v.y); }
Vector2 operator*(float s) const { return Vector2(x * s, y * s); }
float operator*(const Vector2& v) const { return x * v.x + y * v.y; }
float length() const { return sqrt(x * x + y * y); }
Vector2 normalize() const { return Vector2(x / length(), y / length()); }
};
// 定义二维图形结构体
struct Shape {
Vector2 position;
Vector2 scale;
float angle;
Shape() : position(Vector2()), scale(Vector2(1, 1)), angle(0) {}
};
// 实现平移变换
void translate(Shape& shape, const Vector2& offset) {
shape.position = shape.position + offset;
}
// 实现旋转变换
void rotate(Shape& shape, float angle) {
shape.angle += angle;
}
// 实现缩放变换
void scale(Shape& shape, const Vector2& factor) {
shape.scale = shape.scale * factor;
}
int main() {
// 创建一个二维图形
Shape shape;
// 设置初始位置和缩放比例
shape.position = Vector2(0, 0);
shape.scale = Vector2(2, 2);
// 平移变换
Vector2 offset(1, 1);
translate(shape, offset);
// 旋转变换
float angle = M_PI / 4;
rotate(shape, angle);
// 缩放变换
Vector2 factor(0.5, 0.5);
scale(shape, factor);
// 输出变换后的结果
cout << "Position: (" << shape.position.x << ", " << shape.position.y << ")" << endl;
cout << "Scale: (" << shape.scale.x << ", " << shape.scale.y << ")" << endl;
cout << "Angle: " << shape.angle << endl;
return 0;
}
```
在这个示例中,我们定义了一个二维向量结构体和一个二维图形结构体,然后实现了平移、旋转和缩放变换的函数。在主函数中,我们创建了一个二维图形,并对其进行了平移、旋转和缩放变换,最后输出变换后的结果。
注意:在实现旋转变换时,我们使用了数学库中的π常量来表示角度,需要包含cmath头文件。