计算机图形学实践二维几何变换
时间: 2025-05-16 21:44:44 浏览: 13
### 计算机图形学中的二维几何变换
#### 平移变换
平移是一种基本的几何变换,用于将对象从一个位置移动到另一个位置。通过向量加法实现,假设有一个点 \(P(x, y)\),将其沿 \(X\) 轴方向平移 \(T_x\) 单位,沿 \(Y\) 轴方向平移 \(T_y\) 单位,则新的坐标为 \((x', y') = (x + T_x, y + T_y)\)[^1]。
以下是 Python 的平移代码示例:
```python
def translate_point(point, tx, ty):
"""
对给定点执行平移操作。
参数:
point: 原始点的坐标元组 (x, y)
tx: X 方向上的平移距离
ty: Y 方向上的平移距离
返回:
新坐标的元组 (x', y')
"""
x_new = point[0] + tx
y_new = point[1] + ty
return (x_new, y_new)
# 示例调用
original_point = (2, 3)
translated_point = translate_point(original_point, 5, -7)
print(f"Translated Point: {translated_point}")
```
---
#### 缩放变换(比例变换)
缩放变换可以改变物体的大小。对于一个点 \(P(x, y)\),如果要相对于原点进行缩放,其新坐标计算方式如下:\((x', y') = (S_x \cdot x, S_y \cdot y)\)[^3]。其中,\(S_x\) 和 \(S_y\) 是分别沿着 \(X\) 轴和 \(Y\) 轴的比例因子。
Python 中的缩放示例代码如下:
```python
def scale_point(point, sx, sy):
"""
对给定点执行缩放操作。
参数:
point: 原始点的坐标元组 (x, y)
sx: X 方向上缩放的比例因子
sy: Y 方向上缩放的比例因子
返回:
新坐标的元组 (x', y')
"""
x_new = point[0] * sx
y_new = point[1] * sy
return (x_new, y_new)
# 示例调用
scaled_point = scale_point(translated_point, 2.0, 0.5)
print(f"Scaled Point: {scaled_point}")
```
---
#### 旋转变换
旋转变换围绕某个中心点旋转一定角度。设旋转角为 \(\theta\),则任意一点 \(P(x, y)\) 经过逆时针旋转后的坐标为:
\[ x' = x \cos{\theta} - y \sin{\theta}, \quad y' = x \sin{\theta} + y \cos{\theta} \][^3]
下面是 Python 的旋转变换代码示例:
```python
import math
def rotate_point(point, angle_degrees):
"""
对给定点执行绕原点的旋转变换。
参数:
point: 原始点的坐标元组 (x, y)
angle_degrees: 顺时针旋转的角度(单位:度数)
返回:
新坐标的元组 (x', y')
"""
theta_rad = math.radians(angle_degrees)
cos_theta = math.cos(theta_rad)
sin_theta = math.sin(theta_rad)
x_new = point[0] * cos_theta - point[1] * sin_theta
y_new = point[0] * sin_theta + point[1] * cos_theta
return (x_new, y_new)
# 示例调用
rotated_point = rotate_point(scaled_point, 45)
print(f"Rotated Point: {rotated_point}")
```
---
#### OpenGL 实现二维几何变换
在 OpenGL 中,可以通过矩阵运算来完成上述变换。例如,在正方形上应用平移、缩放和旋转的操作:
```cpp
#include <GL/glut.h>
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0); // 设置颜色为红色
glBegin(GL_QUADS);
glVertex2f(-0.5, -0.5); // 左下角
glVertex2f(0.5, -0.5); // 右下角
glVertex2f(0.5, 0.5); // 右上角
glVertex2f(-0.5, 0.5); // 左上角
glEnd();
// 应用变换
glTranslatef(0.8, 0.8, 0.0); // 平移
glScalef(0.5, 0.5, 1.0); // 缩放
glRotatef(45.0, 0.0, 0.0, 1.0); // 旋转
glColor3f(0.0, 1.0, 0.0); // 设置颜色为绿色
glBegin(GL_QUADS);
glVertex2f(-0.5, -0.5);
glVertex2f(0.5, -0.5);
glVertex2f(0.5, 0.5);
glVertex2f(-0.5, 0.5);
glEnd();
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutCreateWindow("2D Transformations");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
```
此代码展示了如何使用 `glTranslatef` 进行平移[^2],`glScalef` 进行缩放,以及 `glRotatef` 进行旋转。
---
阅读全文
相关推荐
















