UE4 截图并保存(C++实现)
时间: 2023-08-12 07:40:52 浏览: 133
c++调用笔记本电脑自带摄像头或外接摄像头,后续会实现截图保存功能,平台为VC6.0.zip
你可以使用以下代码实现在UE4中截取屏幕并保存为图片:
```cpp
UTexture2D* UScreenshotFunctionLibrary::TakeScreenshot(UObject* WorldContextObject, int32 Width, int32 Height)
{
// Get the player controller
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(WorldContextObject, 0);
if (!PlayerController)
{
return nullptr;
}
// Take the screenshot
FViewport* Viewport = GEngine->GameViewport->Viewport;
TArray<FColor> Bitmap;
bool bScreenshotSuccessful = Viewport->ReadPixels(Bitmap, FReadSurfaceDataFlags(), FIntRect(0, 0, Width, Height));
if (!bScreenshotSuccessful)
{
return nullptr;
}
// Create the texture
UTexture2D* Texture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);
Texture->AddToRoot(); // Make sure the texture isn't garbage collected
Texture->UpdateResource();
// Copy the bitmap data to the texture
uint8* MipData = static_cast<uint8*>(Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE));
for (int32 Y = 0; Y < Height; Y++)
{
for (int32 X = 0; X < Width; X++)
{
int32 Index = Y * Width + X;
MipData[Index * 4 + 0] = Bitmap[Index].B;
MipData[Index * 4 + 1] = Bitmap[Index].G;
MipData[Index * 4 + 2] = Bitmap[Index].R;
MipData[Index * 4 + 3] = Bitmap[Index].A;
}
}
Texture->PlatformData->Mips[0].BulkData.Unlock();
// Save the texture to a file
FString Filename = FPaths::ProjectDir() / TEXT("Screenshots") / FDateTime::Now().ToString(TEXT("yyyy-MM-dd_HH-mm-ss")) + TEXT(".png");
FFileHelper::SaveObjectAsPNG(Texture, *Filename);
return Texture;
}
```
此代码通过读取屏幕像素并将其复制到一个临时纹理中,最后将纹理保存为 PNG 文件。你可以调用此函数来截取当前屏幕并保存为文件。
注意:你需要在项目设置中启用 "With Editor" 选项,以便在运行时允许截屏。
阅读全文