记录备用
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "MyFunctions.generated.h"
UCLASS()
class EVENTTEST_API UMyFunctions : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
static FDelegateHandle DelegateHandle;
UFUNCTION(BlueprintCallable)
static void CaptureScreenshot();
static void OnScreenshotCompleteToPng(int32 InWidth, int32 InHeight, const TArray<FColor>& InColor);
static void OnScreenshotCompleteToJpg(int32 InWidth, int32 InHeight, const TArray<FColor>& InColor);
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyFunctions.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
#include "ImageUtils.h"
FDelegateHandle UMyFunctions::DelegateHandle = {};
void UMyFunctions::CaptureScreenshot()
{
if(GEngine && GEngine->GameViewport){}
//DelegateHandle = UGameViewportClient::OnScreenshotCaptured().AddStatic(&OnScreenshotCompleteToPng);
DelegateHandle = UGameViewportClient::OnScreenshotCaptured().AddStatic(&OnScreenshotCompleteToJpg);
GEngine->GameViewport->Exec(nullptr, TEXT("HighResShot 1080x720"), *GLog);
}
void UMyFunctions::OnScreenshotCompleteToPng(int32 InWidth, int32 InHeight, const TArray<FColor>& InColors)
{
FString ScreenShotName = FPaths::ProjectContentDir()+ TEXT("test.png");
TArray<uint8> CompressBitmap;
FImageUtils::CompressImageArray(InWidth,InHeight,InColors,CompressBitmap);
FFileHelper::SaveArrayToFile(CompressBitmap,*ScreenShotName);
UE_LOG(LogTemp,Warning,TEXT("maoguo->保存成功"));
UGameViewportClient::OnScreenshotCaptured().Remove(DelegateHandle);
}
inline void UMyFunctions::OnScreenshotCompleteToJpg(int32 InWidth, int32 InHeight, const TArray<FColor>& InColors)
{
FString ScreenShotName = FPaths::ProjectContentDir()+ TEXT("test.jpg");
IImageWrapperModule& ImageWrapperModule = FModuleManager::Get().LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::JPEG);
if(ImageWrapper->SetRaw(InColors.GetData(),InColors.Num() * sizeof(FColor),
InWidth,InHeight,ERGBFormat::BGRA,8))
{
int32 Quality = 100;
FFileHelper::SaveArrayToFile(ImageWrapper->GetCompressed(Quality),*ScreenShotName);
}
UGameViewportClient::OnScreenshotCaptured().Remove(DelegateHandle);
}
需要注意的地方:
- 如果编译报错,有关于ImageWrapper的,那么在项目配置中加入ImageWrapper模块
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore","ImageWrapper"});
原文说要引入这个模块,但是我UE4.27.2中,没有引入也没有报错
2. 蓝图函数库中要暴露给蓝图使用的函数必须为static(非static函数,蓝图调用的时候必须要有通过对象,就是我们在大部分节点中看到的第一个参数Target),例如代码中的CaptureScreenshot(),还有代码中AddStatic中的函数也必须时static