c ++坐标变化(像素1920 x 1080到640 x 480)

时间:2014-11-24 19:43:12

标签: c++ c++11 2d

我正在开发一个可以在不同视频模式下绘制矩形的小程序(例如1920 x 1080 - > 640 x 480)。我可以调整一个矩形的大小。但我陷入困境,因为我无法找到一个明确的方法来解决问题。我目前正在尝试创建一个矩阵来对像素执行缩放操作,但我无法得到正确的答案。部分问题似乎是TransformMatrix::transform无法正确缩放。

#include <iostream>


typedef struct _Pixel
{
      _Pixel():X(1920)
      ,Y(1080)
      {}
      unsigned X;
      unsigned Y;
}Pixel;

    typedef struct TransformMatrix
    {
      constexpr TransformMatrix(const float aWeigth = 0.3f
                                ,const float aHeigth = 0.225f):W(aWeigth)
      ,H(aHeigth)
      {}
      void transform( const Pixel & aPixel)
      {
        auto x_value=static_cast<float>(aPixel.X)*W;
        auto y_value=static_cast<float>(aPixel.Y)*H;

        std::cout<<"x_value: "<<x_value<<std::endl;
        std::cout<<"y_value: "<<y_value<<std::endl;

      }
      const float W;
      const float H;

    }TransformMatrix;

    int main()
    {
      Pixel aPixel;
      TransformMatrix _TransformMatrix;
      _TransformMatrix.transform(aPixel);
      return 0;
    }

实际结果:

  

x_value:576
  y_value:243

预期结果:

  

x_value:640
  y_value:480

如何执行正确的操作?这只是基础的变化吗? 我应该只进行缩放还是进行转换操作?

1 个答案:

答案 0 :(得分:4)

Wokay,因为人们催促我,让我解释一下这里最重要的风格改进:

  • 命名:不要使用下划线开始名称:它是非法的,程序会调用未定义的行为
  • struct tags:它们是C的东西,自C ++ 98以来在C ++中已经过时了
  • 单一责任原则 - 不要使转换功能打印事物
  • 使Pixel结构能够自行打印(使用operator<<进行iostreams)
  • 纯函数:make transform返回修改后的值,而不是改变参数。通常,这会使代码更安全,并且可以实现一类优化。在极少数情况下,您想要就地更新像素,只需编写

    即可
    pixel = transform(pixel); // the optimizer will see right through this
    
  • 使TransformMatrix成为一个可调用的对象(通过将transform实现为operator()代替。这样,您可以简单地将其用作函数,例如在算法中:

     std::vector<Pixel> poly1, poly2;
     std::transform(poly1.begin(), poly1.end(), 
           back_inserter(poly2), TransformMatrix());
    

    只需将poly1中的所有像素转换为poly2。

为读者练习:命名TransformMatrix,使其完成所说的内容。现在,它更像ScalePixel

<强> Live On Coliru

#include <iostream>

struct Pixel {
    Pixel(unsigned x = 1920, unsigned y = 1080) : X(x), Y(y) {}
    unsigned X;
    unsigned Y;

    friend std::ostream& operator<<(std::ostream& os, Pixel const& p) {
        return os << "Pixel(" << p.X << ", " << p.Y << ")";
    }
};

struct TransformMatrix {
    constexpr TransformMatrix(float aWidth = 640/1920.f, float aHeigth = 480/1080.f) : W(aWidth), H(aHeigth) {}

    Pixel operator()(const Pixel &aPixel) const {
        return { static_cast<unsigned>(aPixel.X * W), static_cast<unsigned>(aPixel.Y * H) };
    }
    float W;
    float H;
};

int main() {
    Pixel aPixel;
    TransformMatrix xfrm;

    std::cout << aPixel << " -> " << xfrm(aPixel) << "\n";
}

打印:

Pixel(1920, 1080) -> Pixel(640, 480)