首页 > 解决方案 > 如何在旋转前获取旋转坐标的位置?

问题描述

我正在尝试旋转图像,但旋转后的图像有一些孔或缺少像素。为了获得应该填充缺失像素的颜色,我需要获取缺失像素在未旋转图像中的位置。

为了计算旋转后的像素坐标,我这样做

double rotationAsRadiant = Math.toRadians( 360 - rotationInDegrees );
double cos = Math.cos( rotationAsRadiant );
double sin = Math.sin( rotationAsRadiant );
int xAfterRotation = (int)( x * cos + y * sin );
int yAfterRotation = (int)( -x * sin + y * cos );

如何获得用于计算 xAfterRotation 和 yAfterRotation 的 x 和 y?

标签: javaalgorithmmathrotation

解决方案


反转公式,如下所示:

double rotationAsRadiant = Math.toRadians( rotationInDegrees );
double cos = Math.cos( rotationAsRadiant );
double sin = Math.sin( rotationAsRadiant );
for (int xAfter = 0; xAfter < width; xAfter++) {
    for (int yAfter = 0; yAfter < height; yAfter++) {
        int xBefore = (int)( xAfter * cos + yAfter * sin );
        int yBefore = (int)( -xAfter * sin + yAfter * cos );
        // paint pixel xAfter/yAfter using original from xBefore/yBefore
        ...
    }
}

这样,您肯定会填充结果图像的所有像素,原始像素最接近确切位置。不会有洞。

您最初的方法是由“给定源像素在目标图像中的位置?”这个问题驱动的。无法保证结果将覆盖所有像素(您已经看到了孔)。

我的方法是“对于给定的目标像素,我在哪里可以找到它的来源?”这个问题。


推荐阅读