如果指定了 CutBox,就截取屏幕上一小块,如果没有指定CutBox,就截取整屏。
// 截屏。
bool ScreenShots(UWorld* pWorld, const FBox2D* CutBox/*= nullptr*/)
{
if (pWorld == NULL)
{
return false;
}
UGameViewportClient* pViewport = Cast<UGameViewportClient>(
pWorld ? pWorld->GetGameViewport() : GEngine->GameViewport);
if (pViewport == NULL)
{
return false;
}
FVector2D vSize = FVector2D::ZeroVector;
pViewport->GetViewportSize(vSize);
TArray<FColor> Bitmap;
bool bScreenshotSuccessful = false;
TSharedPtr<SWindow> WindowPtr = pViewport->GetWindow();
if (FSlateApplication::IsInitialized())
{
TSharedRef<SWidget> WindowRef = WindowPtr.ToSharedRef();
FIntVector IntVector = FIntVector(vSize.X, vSize.Y, 0);
bScreenshotSuccessful = FSlateApplication::Get().TakeScreenshot(
WindowRef, Bitmap, IntVector);
}
for (FColor& Color : Bitmap)
{
Color.A = 255;
}
TArray<FColor>* RealMap = &Bitmap;
bool bNeedCut = (CutBox != NULL && CutBox->bIsValid);
int32 nSizeX = vSize.X, nSizeY = vSize.Y;
TArray<FColor> CutBitmap, CutBitmap2;
if (bNeedCut)
{
nSizeX = CutBox->GetSize().X;
nSizeY = CutBox->GetSize().Y;
RealMap = &CutBitmap;
for (int32 i = CutBox->Min.Y; i < CutBox->Max.Y; i++)
{
for (int32 j = CutBox->Min.X; j < CutBox->Max.X; j++)
{
CutBitmap.Add(Bitmap[i * vSize.X + j]);
}
}
}
FString sFileName = FPaths::ProjectSavedDir();
sFileName.Append(TEXT("/TempImage.png"));
sFileName.ReplaceInline(TEXT("\\"), TEXT("/"));
sFileName.ReplaceInline(TEXT("//"), TEXT("/"));
TArray<uint8> CompressedBitmap;
FImageUtils::CompressImageArray(nSizeX, nSizeY, *RealMap, CompressedBitmap);
if (!CompressedBitmap.IsEmpty())
{
FFileHelper::SaveArrayToFile(CompressedBitmap, *sFileName);
}
return true;
}