整理了下,结合知乎上的一篇分享和自己的理解,最后总结出的一份带UI截图的代码,因为开发时间跨度有点大,中间有几天去玩游戏了,忘记之前参考的网页了,如果有知道的,欢迎留言补充。
头文件:
UFUNCTION(BlueprintCallable, Category= "PuzzleFunction")static void TackShot(const UObject* World, FString FileName);
CPP文件:
void UPuzzleFunctionLibrary::TackShot(const UObject* World, FString FileName)
{if (!GetPuzzleHud(World)->MainUI){return;}// 获取主UI的指针TSharedRef<SWidget> MainUI = GetPuzzleHud(World)->MainUI->TakeWidget();// 准备用于存储原始数据和输出尺寸的变量TArray<FColor> RawData;FIntVector OutSize;// 尝试截取屏幕快照bool bScreenshotSuccessful = FSlateApplication::Get().TakeScreenshot(MainUI, RawData, OutSize);if (bScreenshotSuccessful){// 构建保存截图的文件名FString ScreenShotName = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Images"), FileName);// 确保目录存在IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();FString DirectoryPath = FPaths::GetPath(ScreenShotName);if (!PlatformFile.DirectoryExists(*DirectoryPath)){PlatformFile.CreateDirectory(*DirectoryPath);}// 压缩图像数据TArray<uint8> CompressedBitmap;FImageUtils::ThumbnailCompressImageArray(OutSize.X, OutSize.Y, RawData, CompressedBitmap);// 将压缩后的图像数据保存到文件FFileHelper::SaveArrayToFile(CompressedBitmap, *ScreenShotName);}}