UE4 将ReadPixels的内容保存到数组中(C++实现)
时间: 2023-12-20 07:07:27 浏览: 196
在UE4中,可以通过以下步骤将ReadPixels的内容保存到数组中:
1. 创建一个RenderTarget2D对象,并将其设置为需要读取像素的渲染目标。例如:
```cpp
UTextureRenderTarget2D* RenderTarget = NewObject<UTextureRenderTarget2D>();
RenderTarget->InitAutoFormat(Width, Height);
```
2. 在需要读取像素的时候,使用RenderTarget作为渲染目标,并使用SceneCaptureComponent2D组件进行截图。例如:
```cpp
USceneCaptureComponent2D* SceneCapture = NewObject<USceneCaptureComponent2D>();
SceneCapture->TextureTarget = RenderTarget;
SceneCapture->Activate();
FViewport* Viewport = GEngine->GameViewport->Viewport;
Viewport->Draw();
FTextureRenderTargetResource* RTResource = RenderTarget->GameThread_GetRenderTargetResource();
FReadSurfaceDataFlags ReadPixelFlags(RCM_UNorm, CubeFace_MAX);
ReadPixelFlags.SetLinearToGamma(true);
TArray<FColor> PixelData;
RTResource->ReadPixels(PixelData, ReadPixelFlags);
```
3. 最后,将像素数据保存到一个数组中,即可完成ReadPixels的内容保存。例如:
```cpp
uint32 Size = Width * Height;
uint8* Data = (uint8*)FMemory::Malloc(Size * 4);
for (uint32 i = 0; i < Size; i++)
{
Data[i * 4] = PixelData[i].R;
Data[i * 4 + 1] = PixelData[i].G;
Data[i * 4 + 2] = PixelData[i].B;
Data[i * 4 + 3] = PixelData[i].A;
}
```
注意:以上代码仅供参考,具体实现需要根据项目的实际情况进行调整。
阅读全文