1.创建蓝图小部件:WBP_ValueGauge
2.打开小部件蓝图,编译出错:
原因是没有跟C++绑定的变量:
2.所以,要先创建这两个部件:
(1)拖入“画布”
(2)拖入进度条和文本组件,将他们重命名为:ProgressBar和ValueText
这样,就可以编译了!
(3)调整尺寸
A.进度条:
锚点(ctrl+shift)
B.文本组件:居中对齐、根据内容调整大小
调整字体高度为:22
(4)但长度不好调整,只好再在外面加一个尺寸框:
(5)调整进度条的颜色:
这时,我发现代码中,初始颜色写死了,没办法在蓝图中动态改变进度条的颜色:
所以,再继续更改代码,以下是修改后的代码实现,增加了初始颜色设置和亮度渐变功能:
Source/Crunch/Public/UI/Widget/ValueGauge.h:
// Copyright@ChenChao
#pragma once
#include "CoreMinimal.h"
#include "UI/Widget/CUserWidget.h"
#include "ValueGauge.generated.h"
class UTextBlock;
class UProgressBar;
UCLASS()
class CRUNCH_API UValueGauge : public UCUserWidget
{
GENERATED_BODY()
public:
virtual void NativePreConstruct() override;
void SetValue(float NewValue, float NewMaxValue);
// 设置初始颜色
UFUNCTION(BlueprintCallable, Category="Appearance")
void SetBaseColor(FLinearColor NewBaseColor);
private:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Visual", meta=(AllowPrivateAccess))
FLinearColor BaseColor = FLinearColor::White;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Visual", meta=(AllowPrivateAccess))
float MinBrightness = 0.3f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Visual", meta=(AllowPrivateAccess))
float MaxBrightness = 1.0f;
UPROPERTY(meta=(BindWidget))
TObjectPtr<UProgressBar> ProgressBar;
UPROPERTY(meta=(BindWidget))
TObjectPtr<UTextBlock> ValueText;
};
Source/Crunch/Private/UI/Widget/ValueGauge.cpp:
#include "UI/Widget/ValueGauge.h"
#include "Components/ProgressBar.h"
#include "Components/TextBlock.h"
void UValueGauge::NativePreConstruct()
{
Super::NativePreConstruct();
if(ProgressBar) ProgressBar->SetFillColorAndOpacity(BaseColor);
}
void UValueGauge::SetBaseColor(FLinearColor NewBaseColor)
{
BaseColor = NewBaseColor;
if(ProgressBar) ProgressBar->SetFillColorAndOpacity(BaseColor);
}
void UValueGauge::SetValue(float NewValue, float NewMaxValue)
{
if (NewMaxValue == 0) return;
const float Percent = FMath::Clamp(NewValue / NewMaxValue, 0.0f, 1.0f);
// 计算亮度变化
float Brightness = FMath::Lerp(MinBrightness, MaxBrightness, Percent);
FLinearColor CurrentColor = BaseColor;
CurrentColor.R *= Brightness;
CurrentColor.G *= Brightness;
CurrentColor.B *= Brightness;
if(ProgressBar)
{
ProgressBar->SetPercent(Percent);
ProgressBar->SetFillColorAndOpacity(CurrentColor);
}
if (ValueText)
{
ValueText->SetText(FText::Format(
FTextFormat::FromString("{0}/{1}"),
FText::AsNumber(NewValue),
FText::AsNumber(NewMaxValue)
));
}
}
主要改进:
1. 新增SetBaseColor方法设置初始颜色
2. 通过亮度系数控制颜色深浅变化
3. 可配置最小/最大亮度值。使用时可通过蓝图或代码动态修改基础颜色。
效果: