QT中基于QMatrix4x4与QVector3D的三维坐标变换类实现
1.头文件
#ifndef COORDINATETRANSFORM3D_H
#define COORDINATETRANSFORM3D_H
#include <QVector3D>
#include <QMatrix4x4>
class CoordinateTransform3D {
public:
CoordinateTransform3D();
// 设置平移
void translate(double dx, double dy, double dz);
// 设置缩放
void scale(double sx, double sy, double sz);
// 设置旋转
void rotateX(double angle); // 绕X轴旋转
void rotateY(double angle); // 绕Y轴旋转
void rotateZ(double angle); // 绕Z轴旋转
// 应用变换到点
QVector3D transform(const QVector3D &point) const;
private:
QMatrix4x4 m_transform; // Qt的4x4矩阵类
};
#endif // COORDINATETRANSFORM3D_H
2.实现文件
#include "CoordinateTransform3D.h"
CoordinateTransform3D::CoordinateTransform3D() {
// 初始化变换为单位矩阵
m_transform.setToIdentity();
}
void CoordinateTransform3D::translate(double dx, double dy, double dz) {
m_transform.translate(dx, dy, dz);
}
void CoordinateTransform3D::scale(double sx, double sy, double sz) {
m_transform.scale(sx, sy, sz);
}
void CoordinateTransform3D::rotateX(double angle) {
m_transform.rotate(angle, 1.0, 0.0, 0.0);
}
void CoordinateTransform3D::rotateY(double angle) {
m_transform.rotate(angle, 0.0, 1.0, 0.0);
}
void CoordinateTransform3D::rotateZ(double angle) {
m_transform.rotate(angle, 0.0, 0.0, 1.0);
}
QVector3D CoordinateTransform3D::transform(const QVector3D &point) const {
QVector4D homogenousPoint(point.x(), point.y(), point.z(), 1.0);
QVector4D transformedPoint = m_transform * homogenousPoint;
return QVector3D(transformedPoint.x() / transformedPoint.w(),
transformedPoint.y() / transformedPoint.w(),
transformedPoint.z() / transformedPoint.w());
}
3. 测试文件
#include <QCoreApplication>
#include <QVector3D>
#include <QDebug>
#include "CoordinateTransform3D.h"
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
CoordinateTransform3D transform;
// 设置变换
transform.translate(10, 20, 30);
transform.scale(2, 2, 2);
transform.rotateX(45); // 绕X轴旋转45度
transform.rotateY(30); // 绕Y轴旋转30度
transform.rotateZ(60); // 绕Z轴旋转60度
// 原始点
QVector3D originalPoint(1, 1, 1);
QVector3D transformedPoint = transform.transform(originalPoint);
// 输出变换后的点
qDebug() << "Original Point:" << originalPoint;
qDebug() << "Transformed Point:" << transformedPoint;
return a.exec();
}