This method is to directly use C++ to adjust the texture
1. Create a new C++ class and inherit UserWidget
The picture below is newly created, named CanvasUserWidget
2. Modify the CanvasUserWidget class
CanvasUserWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Components/Image.h"
#include "CanvasUserWidget.generated.h"
/**
*
*/
UCLASS()
class WATERWALL426_API UCanvasUserWidget : public UUserWidget
{
GENERATED_BODY()
public:
UCanvasUserWidget(const FObjectInitializer& ObjectInitializer);
virtual void NativeConstruct()override;
UFUNCTION(BlueprintCallable)
void CreateTexture();
UFUNCTION(BlueprintCallable)
void Draw(FVector2D Pos);
private:
//Iamge控件
UImage* pImage;
UPROPERTY(EditAnywhere)
UTexture2D* pTexture;
};
CanvasUserWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "CanvasUserWidget.h"
UCanvasUserWidget::UCanvasUserWidget(const FObjectInitializer& ObjectInitializer) :Super(ObjectInitializer)
{
}
void UCanvasUserWidget::NativeConstruct()
{
Super::NativeConstruct();
}
void UCanvasUserWidget::CreateTexture()
{
if (pTexture)return;
//create
pTexture = UTexture2D::CreateTransient(1920, 1080);
pTexture->UpdateResource();
//set brush
pImage = Cast<UImage>(GetWidgetFromName(FName(TEXT("Image_Canvas"))));
pImage->SetBrushFromTexture(pTexture);
}
void UCanvasUserWidget::Draw(FVector2D Pos)
{
if (!pTexture)return;
FTexture2DMipMap& mipmap = pTexture->PlatformData->Mips[0];
unsigned char* Data = (unsigned char*)mipmap.BulkData.Lock(LOCK_READ_WRITE);
int texturex = pTexture->PlatformData->SizeX;
int texturey = pTexture->PlatformData->SizeY;
float bPerUV_v = 1.0 / texturey;
for (int32 y = 0; y < texturey; y++)
{
for (int32 x = 0; x < texturex; x++)
{
if (x<= Pos.X + 4&&x>= Pos.X - 4&&y<= Pos.Y+4&& y >= Pos.Y - 4)
{
Data[(y * texturex + x) * 4 + 0] = 0;//B
Data[(y * texturex + x) * 4 + 1] = 0;//G
Data[(y * texturex + x) * 4 + 2] = 255;//R
Data[(y * texturex + x) * 4 + 3] = 255;//A 0:全透明;255:全不透明
}
}
}
mipmap.BulkData.Unlock();
pTexture->UpdateResource();
//update
pImage->SetBrushFromTexture(pTexture);
}
3. Create a new blueprint and select CanvasUserWidget
Add a Canvas Artboard and an Image control, name the image Image_Canvas
add function
4. Create a new Pawn and GameMode
Slightly (lazy...please read the previous one)
5. Add function in Pawn
6. Effect