动态创建Texture2D

直接贴代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

UTexture2D* ULibNextBridge::CreateTexture2dAsset_ByPixels(FString TextureName, FString Path, const TArray<FColor>& FillPixels,
int32 Width, int32 Height, EPixelFormat PixelFormat, bool sRGB)
{
TArray<FColor> Pixels = FillPixels;
//创建非重复的名字
FString UniquePackageName;
FString UniqueAssetName;
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
AssetToolsModule.Get().CreateUniqueAssetName(Path + TextureName, TEXT(""), UniquePackageName, UniqueAssetName);
//创建包
UPackage* Package = CreatePackage( *UniquePackageName);
Package->FullyLoad();
//创建贴图资源
UTexture2D* res = NewObject<UTexture2D>(Package, *UniqueAssetName, RF_Public | RF_Standalone | RF_MarkAsRootSet);
res->AddToRoot();
res->SRGB = sRGB;
res->MipGenSettings = TMGS_NoMipmaps;
//创建PlatformData数据
FTexturePlatformData* PlatformData = new FTexturePlatformData();
PlatformData->SizeX = Width;
PlatformData->SizeY = Height;
PlatformData->PixelFormat = PixelFormat;
res->SetPlatformData(PlatformData);
res->UpdateResource();
FTexture2DMipMap* Mip = new FTexture2DMipMap();
res->GetPlatformData()->Mips.Add(Mip);
Mip->SizeX = Width;
Mip->SizeY = Height;
//写入像素数据
Mip->BulkData.Lock(LOCK_READ_WRITE);
uint8* TextureData = static_cast<uint8*>(Mip->BulkData.Realloc(Width * Height * sizeof(FColor)));
FMemory::Memcpy(TextureData, Pixels.GetData(), Width * Height * sizeof(FColor));
Mip->BulkData.Unlock();

res->UpdateResource();
//初始化source数据
res->Source.Init(Width,Height,1, 1, ETextureSourceFormat::TSF_BGRA8, reinterpret_cast<uint8*>(Pixels.GetData()));
res->UpdateResource();
Package->MarkPackageDirty();
//注册资源
FAssetRegistryModule::AssetCreated(res);
//创建LongPackageName, 并保存包
FString PackageFileName = FPackageName::LongPackageNameToFilename(UniquePackageName, FPackageName::GetAssetPackageExtension());
FSavePackageArgs SavePackageArgs;
SavePackageArgs.TopLevelFlags = RF_Public | RF_Standalone;
SavePackageArgs.SaveFlags = SAVE_NoError;
bool bSaved = UPackage::SavePackage(Package,NULL,*PackageFileName,SavePackageArgs);
check(bSaved)
return res;
}