虚幻4动态加载PNG给Texture2D

来源:互联网 发布:淘宝宝贝权重查询软件 编辑:程序博客网 时间:2024/06/05 05:22
本教程适用于4.17以前的版本,4.18以上不兼容

头文件:
#include "ImageWrapper.h"

/*载入PNG贴图*/
UFUNCTION(BlueprintCallable, Category = "GameSetting")
UTexture2D* GetPngFromPath(const FString& FullFilePath, bool& IsValid, int32& Width, int32& Height);
/*载入贴图*/
UTexture2D* GetTexture2DFromPath(const FString& FullFilePath, EImageFormat::Type ImageFormat, bool& IsValid, int32& Width, int32& Height);



源文件:
UTexture2D* AAKGameGameModeBase::GetPngFromPath(const FString& FullFilePath, bool& IsValid, int32& Width, int32& Height)
{
return GetTexture2DFromPath(FullFilePath, EImageFormat::Type::PNG,IsValid,Width,Height);
}

UTexture2D* AAKGameGameModeBase::GetTexture2DFromPath(const FString& FullFilePath, EImageFormat::Type ImageFormat, bool& IsValid, int32& Width, int32& Height)
{
IsValid = false;
UTexture2D* LoadedT2D = NULL;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
IImageWrapperPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat);

// 从指定路径的文件加载
TArray<uint8> RawFileData;
if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) return NULL;

// 新建Texture2D
bool valid = ImageWrapper.IsValid();
bool setCompressed = ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num());
if (valid && setCompressed)
{
const TArray<uint8>* UncompressedBGRA = NULL;
if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);

// 检查是否存在
if (!LoadedT2D) return NULL;

// 设置出参
Width = ImageWrapper->GetWidth();
Height = ImageWrapper->GetHeight();

// 复制图像内容
void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(TextureData, UncompressedBGRA->GetData(), UncompressedBGRA->Num());
LoadedT2D->PlatformData->Mips[0].BulkData.Unlock();

// 更新图像
LoadedT2D->UpdateResource();

// 成功
IsValid = true;
return LoadedT2D;
}
}

// 失败
IsValid = false;
return NULL;
}

这个官方的教程也可以尝试下,比较复杂
https://wiki.unrealengine.com/Asynchronous_Image_Loading_from_Disk