UE4 创建一个actor,具有截图保存功能(C++实现)
时间: 2024-03-23 08:39:08 浏览: 104
c++调用笔记本电脑自带摄像头或外接摄像头,后续会实现截图保存功能,平台为VC6.0.zip
可以通过以下步骤在UE4中创建一个Actor并实现截图保存功能:
1. 创建一个继承自Actor的C++类,例如命名为MyActor。
2. 在MyActor.h中添加以下头文件:
```c++
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/Texture2D.h"
```
3. 声明一个TextureRenderTarget2D成员变量和一个Texture2D成员变量:
```c++
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Screenshot")
UTextureRenderTarget2D* ScreenshotRenderTarget;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Screenshot")
UTexture2D* ScreenshotTexture;
```
4. 在MyActor.cpp中重写BeginPlay()函数,创建RenderTarget和Texture:
```c++
void AMyActor::BeginPlay()
{
Super::BeginPlay();
ScreenshotRenderTarget = UGameplayStatics::CreateRenderTarget2D(GetWorld(), 1920, 1080);
ScreenshotTexture = UTexture2D::CreateTransient(1920, 1080);
}
```
5. 在MyActor.cpp中添加一个截图函数:
```c++
void AMyActor::TakeScreenshot()
{
if (ScreenshotRenderTarget != nullptr && ScreenshotTexture != nullptr)
{
FTextureRenderTargetResource* RenderTargetResource = ScreenshotRenderTarget->GameThread_GetRenderTargetResource();
FReadSurfaceDataFlags ReadPixelFlags(RCM_UNorm);
ReadPixelFlags.SetLinearToGamma(true);
TArray<FColor> OutBMP;
RHIReadSurfaceData(RenderTargetResource->GetRenderTargetTexture(), FIntRect(0, 0, ScreenshotRenderTarget->SizeX, ScreenshotRenderTarget->SizeY), OutBMP, ReadPixelFlags);
ScreenshotTexture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
uint8* TextureData = (uint8*)ScreenshotTexture->PlatformData->Mips[0].BulkData.Realloc(OutBMP.Num() * 4);
for (int32 i = 0; i < OutBMP.Num(); i++)
{
TextureData[i * 4 + 0] = OutBMP[i].B;
TextureData[i * 4 + 1] = OutBMP[i].G;
TextureData[i * 4 + 2] = OutBMP[i].R;
TextureData[i * 4 + 3] = OutBMP[i].A;
}
ScreenshotTexture->PlatformData->Mips[0].BulkData.Unlock();
ScreenshotTexture->UpdateResource();
FString FileName = FPaths::ProjectSavedDir() + TEXT("Screenshots/MyScreenshot.png");
FFileHelper::SaveArrayToFile(ScreenshotTexture->PlatformData->Mips[0].BulkData, *FileName);
}
}
```
6. 在MyActor.cpp中添加一个函数,用于在按下某个按键时调用截图函数:
```c++
void AMyActor::CaptureScreenshot()
{
TakeScreenshot();
}
```
7. 在MyActor的Blueprint中添加一个InputComponent,将某个按键与CaptureScreenshot函数绑定即可。
完成以上步骤后,你就可以在UE4中创建一个Actor,并在其中实现截图保存功能了。
阅读全文