UE4 场景中截取图片并保存(C++实现)
时间: 2024-01-27 11:05:04 浏览: 108
在UE4中,你可以使用C++代码来实现截取场景中的图片并保存到本地。具体步骤如下:
1. 创建一个C++类,并继承自AActor类。命名为"ScreenshotActor"。
2. 在"ScreenshotActor.h"文件中添加以下头文件:
```cpp
#include "Engine/Engine.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/GameViewportClient.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
```
3. 在"ScreenshotActor.h"文件中添加以下声明:
```cpp
UCLASS()
class YOURPROJECT_API AScreenshotActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AScreenshotActor();
// Take screenshot and save to file
UFUNCTION(BlueprintCallable, Category = "Screenshot")
void TakeScreenshot();
private:
// The resolution multiplier for the screenshot
UPROPERTY(EditAnywhere, Category = "Screenshot")
int32 ResolutionMultiplier = 1;
};
```
4. 在"ScreenshotActor.cpp"文件中添加以下代码:
```cpp
#include "ScreenshotActor.h"
AScreenshotActor::AScreenshotActor()
{
PrimaryActorTick.bCanEverTick = false;
}
void AScreenshotActor::TakeScreenshot()
{
// Get the game viewport client
UGameViewportClient* ViewportClient = GEngine->GameViewport;
if (ViewportClient)
{
// Get the viewport size
FVector2D Size;
ViewportClient->GetViewportSize(Size);
// Calculate the screenshot resolution
int32 ResolutionX = Size.X * ResolutionMultiplier;
int32 ResolutionY = Size.Y * ResolutionMultiplier;
// Take the screenshot
TArray<FColor> Bitmap;
Bitmap.AddUninitialized(ResolutionX * ResolutionY);
ViewportClient->ReadPixels(Bitmap);
// Create the screenshot texture
UTexture2D* Screenshot = UTexture2D::CreateTransient(ResolutionX, ResolutionY);
Screenshot->CompressionSettings = TC_HDR;
Screenshot->SRGB = false;
Screenshot->AddToRoot();
Screenshot->UpdateResource();
// Copy the pixel data to the texture
uint8* MipData = static_cast<uint8*>(Screenshot->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE));
FMemory::Memcpy(MipData, Bitmap.GetData(), Bitmap.Num() * sizeof(FColor));
Screenshot->PlatformData->Mips[0].BulkData.Unlock();
// Save the screenshot to file
FDateTime Now = FDateTime::Now();
FString Filename = FString::Printf(TEXT("Screenshot_%04d%02d%02d_%02d%02d%02d.png"), Now.GetYear(), Now.GetMonth(), Now.GetDay(), Now.GetHour(), Now.GetMinute(), Now.GetSecond());
FString SaveDirectory = FPaths::GameSavedDir() + TEXT("Screenshots/");
if (!FPaths::DirectoryExists(SaveDirectory))
{
FPlatformFileManager::Get().GetPlatformFile().CreateDirectory(*SaveDirectory);
}
FString FilePath = SaveDirectory + Filename;
FFileHelper::SaveArrayToFile(Screenshot->GetRawImageData(), Screenshot->GetAllocatedSize(), *FilePath);
// Remove the screenshot texture
Screenshot->RemoveFromRoot();
}
}
```
5. 在UE4编辑器中创建一个蓝图,并选择"ScreenshotActor"作为其父类。
6. 在蓝图中添加一个"Take Screenshot"函数,并调用AScreenshotActor::TakeScreenshot()函数。
7. 在场景中放置该蓝图,并运行游戏。当需要截取场景中的图片时,调用蓝图中的"Take Screenshot"函数即可。
注意:在截图之前需要确保场景中的所有元素都已经加载完毕,否则可能会导致截图不完整或者出现其他问题。另外,该实现只适用于PC平台,如果需要支持其他平台,请参考UE4官方文档或者相关论坛。
阅读全文