RenderTarget转Texture2D

MyBlueprintFunctionLibrary.h


#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Engine/TextureRenderTarget2D.h"
#include "MyBlueprintFunctionLibrary.generated.h"

/**
 * 
 */
UCLASS()
class ANDROIDPROJECT_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()

public:
	/**
	 * 将RenderTarget2D转换为Texture2D
	 * @param RenderTarget - 要转换的RenderTarget
	 * @return 转换后的Texture2D,如果转换失败返回nullptr
	 */
	UFUNCTION(BlueprintCallable, Category = "Texture")
	static UTexture2D* ConvertRenderTargetToTexture2D(UTextureRenderTarget2D* RenderTarget);
};

MyBlueprintFunctionLibrary.cpp


#include "MyBlueprintFunctionLibrary.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/Texture2D.h"
#include "RenderUtils.h"

UTexture2D* UMyBlueprintFunctionLibrary::ConvertRenderTargetToTexture2D(UTextureRenderTarget2D* RenderTarget)
{
	if (!RenderTarget)
	{
		return nullptr;
	}

	// 获取RenderTarget的尺寸
	const int32 Width = RenderTarget->SizeX;
	const int32 Height = RenderTarget->SizeY;

	// 创建新的Texture2D
	UTexture2D* NewTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);
	if (!NewTexture)
	{
		return nullptr;
	}

	// 从RenderTarget读取像素数据
	TArray<FColor> SurfData;
	FRenderTarget* RenderTargetResource = RenderTarget->GameThread_GetRenderTargetResource();
	if (!RenderTargetResource || !RenderTargetResource->ReadPixels(SurfData))
	{
		return nullptr;
	}

	// 更新Texture2D的数据
	void* TextureData = NewTexture->GetPlatformData()->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
	FMemory::Memcpy(TextureData, SurfData.GetData(), SurfData.Num() * sizeof(FColor));
	NewTexture->GetPlatformData()->Mips[0].BulkData.Unlock();

	// 更新Texture
	NewTexture->UpdateResource();

	return NewTexture;
}

注意在Build.cs添加

// Fill out your copyright notice in the Description page of Project Settings.

using UnrealBuildTool;

public class AndroidProject : ModuleRules
{
	public AndroidProject(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
	
		PublicDependencyModuleNames.AddRange(new string[]
		{
			"Core", 
			"CoreUObject", 
			"Engine", 
			"InputCore",
			"RenderCore",
			"HTTP"
		});

		PrivateDependencyModuleNames.AddRange(new string[] {  });

		// Uncomment if you are using Slate UI
		// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
		
		// Uncomment if you are using online features
		// PrivateDependencyModuleNames.Add("OnlineSubsystem");

		// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值