【问题标题】:Capturing an area of the screen with cocos2d::RenderTexture and setVirtualViewport使用 cocos2d::RenderTexture 和 setVirtualViewport 捕获屏幕区域
【发布时间】:2018-03-05 01:55:57
【问题描述】:

cocos2d-x 版本:3.16

我想截取屏幕的一个区域,并将其保存在 PNG 文件中。最好的方法是使用RenderTexture,捕获特定区域应该使用setVirtualViewport 方法。文档说:

void setVirtualViewport   (
      const Vec2 & rtBegin,
      const Rect & fullRect,
      const Rect & fullViewport 
  )   

用于将屏幕的一部分抓取到纹理。

参数

  • rtBegin渲染纹理在fullRect上的位置。
  • fullRect 屏幕总尺寸。
  • fullViewport 总视口大小。

我有以下代码,设计分辨率为 1920*1080(我简化了代码以在此处显示,并将值作为常量给出):

unsigned int SIZE_X = 960;
unsigned int SIZE_Y = 540;
unsigned int POS_X = 100;
unsigned int POS_Y = 100;

RenderTexture* texture = RenderTexture::create(SIZE_X, SIZE_Y);
texture->setVirtualViewport(Vec2(POX_X, POS_Y),
                            Rect(0, 0, 1920, 1080),
                            Rect(0, 0, SIZE_X, SIZE_Y));

texture->begin();
this->visit();
texture->end();

texture->saveToFile("test.png", Image::Format::PNG);

我尝试了很多不同的参数组合,但无论我做什么,最多捕获矩形 0、0、SIZE_X、SIZE_Y 中的像素,其余的填充透明像素。偏移量也是错误的(它受屏幕大小和捕获区域之间的比率影响,尽管它不应该)。

这是上面代码的模拟场景的结果,其中红色表示透明像素:

我以红色显示的所有像素都是空的,它们不应该是空的,并且偏移量是错误的:(50, 50) 而不是(100, 100)

你知道如何正确使用setVirtualViewport吗?他们的方法有错误还是我做错了什么?

或者,您是否有其他解决方案来捕获屏幕区域并将其保存到图像或cocos2d::Sprite 中? (不移动Scene的内容)

【问题讨论】:

    标签: c++ cocos2d-x


    【解决方案1】:

    由于我似乎不完全了解函数 setVirtualViewport 的工作原理,或者这个函数可能存在问题,所以这是我想出的一个解决方案,它做同样的事情,即使它可能不是高效:

    • RenderTexture 中捕获整个屏幕。
    • 更改由RenderTexture生成的Sprite的位置,即使它不属于场景所以不可见,将其放在您想要的区域的开头(0 ,0)。
    • 创建第二个RenderTexture,其大小为您要捕获的大小。
    • 访问精灵以在第二个RenderTexture 中渲染它。

    代码如下:

    unsigned int SIZE_X = 960;
    unsigned int SIZE_Y = 540;
    unsigned int POS_X = 100;
    unsigned int POS_Y = 100;
    
    RenderTexture* screenCapture = RenderTexture::create(1920, 1080);
    
    screenCapture->begin();
    this->visit();
    screenCapture->end();
    
    RenderTexture* areaTexture = RenderTexture::create(SIZE_X, SIZE_Y);
    areaTexture->begin();
    screenCapture->getSprite()->setPosition(Vec2(960 - POS_X, 540 - POS_Y));
    screenCapture->getSprite()->visit();
    areaTexture->end();
    
    AreaTexture->saveToFile("test.png", Image::Format::PNG);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      相关资源
      最近更新 更多