【发布时间】:2012-02-19 02:23:12
【问题描述】:
我正在尝试维护然后将转换矩阵用于计算机图形程序。它是一个 3x3 矩阵,用于存储 (x,y) 点的缩放、旋转和平移信息。
我的程序可以处理任何个别情况...即,如果我只缩放或只旋转它可以正常工作。但是,在组合缩放和旋转时它似乎不起作用,我认为这与我如何在代码中组合旋转和缩放有关。该矩阵称为变换,其类型为浮点数。以下方法清除、旋转、缩放和平移(按此顺序)矩阵。
public void clearTransform()
{
transformation[0][0] = 1;transformation[0][1] = 0;transformation[0][2] = 0;
transformation[1][0] = 0;transformation[1][1] = 1;transformation[1][2] = 0;
transformation[2][0] = 0;transformation[2][1] = 0;transformation[2][2] = 1;
}
public void rotate (float degrees)
{
double r = degrees * (Math.PI/180);
float sin = (float)Math.sin(r);
float cos = (float)Math.cos(r);
transformation[0][0] *= cos;
transformation[1][1] *= cos;
if(transformation[0][1] == 0)
transformation[0][1] = -sin;
else
transformation[0][1] *= -sin;
if(transformation[1][0] == 0)
transformation[1][0] = sin;
else
transformation[1][0] *= sin;
}
public void scale (float x, float y)
{
transformation[0][0] *= x;
transformation[1][1] *= y;
}
public void translate (float x, float y)
{
transformation[0][2] += x;
transformation[1][2] += y;
}
对于比例,矩阵包含如下信息:
(Sx, 0, 0) (0, SY, 0) (0, 0, 1)
旋转,像这样:
(cos(theta), -sin(theta), 0) (正弦(θ),余弦(θ),0) (0, 0, 1)
翻译,这个:
(1, 0, 发送) (0, 1, 泰) (0, 0, 1)
我认为我没有正确组合缩放和旋转。这是我实际应用转换的地方:
public float[] transformX(float[] x, float[] y, int n) {
float[] newX = new float[n];
for(int i = 0; i < n; i ++) {
newX[i] = (x[i] * transformation[0][0]) + (y[i] * transformation[0][1]) + transformation[0][2];
}
return newX;
}
public float[] transformY(float[] x, float[] y, int n) {
float[] newY = new float[n];
for(int i = 0; i < n; i ++) {
newY[i] = (x[i] * transformation[1][0]) + (y[i] * transformation[1][1]) + transformation[1][2];
}
return newY;
}
其中x和y是预变换的点数组,n是点的个数
感谢您的帮助!
【问题讨论】:
-
由于您似乎只是在转换两个维度,因此您还可以使用 Java2D
AffineTransform类:docs.oracle.com/javase/tutorial/2d/advanced/transforming.html -
很好,但是
rotate应该是与旧值的矩阵乘法; 0 上的 ifs 无权存在。通常,您需要一个临时矩阵来将新值写入其中。也许你可以从 java 借用现有的代码。 -
我最初将这两个作为 (*= -sin) 和 (*= sin),但如果它们为 0,(应用第一次旋转时总是如此),那么值将保持为 0。
标签: java math graphics matrix transformation