【UE4虛幻】UTexture2D纹理裁剪函数

参数说明:
源2D纹理图片:UTexture2D* SourceTexture
裁剪区域的左上角:const FVector2D TopLeft
裁剪区域的右下角:const FVector2D BottomRight
返回值是裁剪之后的纹理图片

UTexture2D* APointProjection::CropPicture(UTexture2D* SourceTexture,const FVector2D TopLeft, const FVector2D BottomRight)
{
    if (!SourceTexture || !SourceTexture->IsValidLowLevel())
    {
    	UE_LOG(LogTemp, Error, TEXT("value error"));
        return SourceTexture;
    }

    int32 TextureWidth = BottomRight.X - TopLeft.X;
    int32 TextureHeight = BottomRight.Y - TopLeft.Y;

    UE_LOG(LogTemp, Error, TEXT("TextureWidth is %d TextureHeight is %d"), TextureWidth, TextureHeight);
	
	const uint8* FormatedImageData = static_cast<const uint8*>(SourceTexture->PlatformData->Mips[0].BulkData.LockReadOnly());
	
	TUniquePtr<uint8[]> ClippedTextureData(new uint8[TextureWidth * TextureHeight * 4]);
	
	UE_LOG(LogTemp, Error, TEXT("FormatedImageData %p"), FormatedImageData);

	
	for (int32 y = TopLeft.Y; y < BottomRight.Y - 1; y++) //减去一是为了防止类型转换而导致越界
	{
		for (int32 x = TopLeft.X; x < BottomRight.X - 1; x++)
		{
			int32 m_x = x - TopLeft.X;
			int32 m_y = y - TopLeft.Y;

			int32 curPixelIndex1 = (m_y * TextureWidth + m_x);
			int32 curPixelIndex2 = (y * SourceTexture->GetSizeX() + x);

			// 将当前像素颜色添加到像素数组中,注意 BGRA 通道的顺序
			ClippedTextureData[curPixelIndex1 * 4]     = FormatedImageData[curPixelIndex2 * 4];
			ClippedTextureData[curPixelIndex1 * 4 + 1] = FormatedImageData[curPixelIndex2 * 4 + 1];
			ClippedTextureData[curPixelIndex1 * 4 + 2] = FormatedImageData[curPixelIndex2 * 4 + 2];
			ClippedTextureData[curPixelIndex1 * 4 + 3] = FormatedImageData[curPixelIndex2 * 4 + 3];
		}
	}
	
	// 解锁 MipMap
	SourceTexture->PlatformData->Mips[0].BulkData.Unlock();
	

	写操作
	UTexture2D* CropTexture = UTexture2D::CreateTransient(TextureWidth, TextureHeight, SourceTexture->GetPixelFormat());

	void* TextureData = CropTexture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);

	FMemory::Memcpy(TextureData, ClippedTextureData.Get(), sizeof(uint8) * TextureHeight * TextureWidth * 4);

	CropTexture->PlatformData->Mips[0].BulkData.Unlock();

	CropTexture->UpdateResource();

	return CropTexture;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值