原理是将UI组件渲染到材质,再将材质保存为图片。
FString SavePath = FPaths::ProjectDir() + TEXT("Saved/Screenshots/screenshot.png");
FWidgetRenderer* wr = new FWidgetRenderer(true, false);
UUserWidget * widget = FindChild<UUserWidget>(GetRootWidget(), TEXT("SBox_XXXX")); //要截图的组件
TSharedPtr<SWidget> SlateWidget(widget->TakeWidget());
FVector2D boxsize = widget->GetDesiredSize();
UTextureRenderTarget2D* RenderTarget = wr->DrawWidget(SlateWidget.ToSharedRef(),boxsize);
TArray<FColor> OutBMP;
FRenderTarget* RTResource = RenderTarget->GameThread_GetRenderTargetResource();
RTResource->ReadPixels(OutBMP);
FIntPoint destSize(RenderTarget->GetSurfaceWidth(), RenderTarget->GetSurfaceHeight());
TArray<uint8> CompressedBitmap;
FImageUtils::CompressImageArray(destSize.X, destSize.Y, OutBMP, CompressedBitmap);
bool imageSavedOk = FFileHelper::SaveArrayToFile(CompressedBitmap, *SavePath);
发表评论
抢沙发~