【问题标题】:How to get the color of a pixel in an image in C++ (sfml)如何在 C++ (sfml) 中获取图像中像素的颜色
【发布时间】:2018-07-10 03:15:56
【问题描述】:

我正在开发一个简单的赛车游戏,您可以在赛道上驾驶汽车。 轨道是灰色的,背景是绿色的,任何时候我在给定点(汽车前部)的颜色不是灰色的,汽车应该停下来,因为它跑出了轨道。

但是轨道不是用 sfml 绘制的,而是我制作的下载图像。 那么,有没有什么方法可以获取 IMAGE 上像素的颜色,只要 rgb 值匹配?

这是执行此操作的伪代码:

游戏运行时
获取颜色(汽车 x 值,汽车 y 值)
如果颜色不是灰色
汽车停下来

谢谢!

【问题讨论】:

    标签: c++ visual-c++ sfml


    【解决方案1】:

    您可以使用适当的方法:sf::Image::getPixel 获取sf::Image 中像素的sf::Color。它需要 X 和 Y 坐标。

    例子:

    sf::Image track;
    
    if (!track.loadFromFile("track.jpg"))
    {
       // oops, loading failed, handle it
    }
    
    sf::Color color = track.getPixel(0, 0); // gets the color of the upper left corner pixel
    

    【讨论】:

      【解决方案2】:

      您需要使用 sf::Image 的 getPixel(int x, int y) 函数。你的伪代码看起来像这样:

      sf::Image track;
      sf::Color grey_color; // You'll need to define what the grey color is.
                            // Take sf::Color(100, 100, 100) as an example.
      if (!track.loadFromFile("track.jpg")) {
          std::cout << "Uhoh" << std::endl;
      }
      
      while (gameIsRunning) {
          sf::Color color_at_car = track.getPixel(car.getx(), car.gety());
          if (color_at_car != grey_color) {
              car.stop();
          }
      }
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 2013-07-21
        • 2019-07-27
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多