Canvas is a continuation of the simple HUD implemented within Unreal 3. While it isn't so commonly used within shipping games, mostly being replaced by Slate/UMG, it's simple to use, especially when you want to draw text or shapes to the screen. Canvas drawing is still used extensively by console commands used for debugging and performance analysis such as the stat game
and other stat
commands. Refer to Chapter 8, Integrating C++ and the Unreal Editor, for the recipe for creating your own console commands.
<Module>.build.cs
file, and uncomment/add the following line:PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
GameMode
called CustomHUDGameMode
using the editor class wizard. Refer to Chapter 4, Actors and Components, if you need a refresher on doing this.ACustomHUDGameMode();
ACustomHUDGameMode::ACustomHUDGameMode() :AGameMode() { HUDClass = ACustomHUD::StaticClass(); }
CustomHUD
, again using the wizard.override
keyword to the following function:public: virtual void DrawHUD() override;
voidACustomHUD::DrawHUD() { Super::DrawHUD(); Canvas->DrawText(GEngine->GetSmallFont(), TEXT("Test string to be printed to screen"), 10, 10); FCanvasBoxItemProgressBar(FVector2D(5, 25), FVector2D(100, 5)); Canvas->DrawItem(ProgressBar); DrawRect(FLinearColor::Blue, 5, 25, 100, 5); }
CustomHUDGameMode
from the list under GameMode Override:AHUD
.GameMode
, and specify the type of our custom class.UClass
for our new HUD type to the HUDClass
variable. This UClass
is passed onto each player controller as they spawn in, and the controller is then responsible for the AHUD
instance that it creates.GameMode
loading our custom HUD, we need to actually create the said custom HUD class.AHUD
defines a virtual function called DrawHUD()
, which is invoked in every frame to allow us to draw elements to the screen.floatDrawText(constUFont* InFont, constFString&InText, float X, float Y, float XScale = 1.f, float YScale = 1.f, constFFontRenderInfo&RenderInfo = FFontRenderInfo());
DrawText
requires a font to draw with. The default font used by stat
and other HUD drawing commands in the engine code is actually stored in the GEngine
class, and can be accessed by using the GetSmallFont
function, which returns an instance of the UFont
as a pointer.DrawText
is a function that allows you to directly pass in the data that is to be displayed.DrawItem
function is a Visitor implementation that allows you to create an object that encapsulates the information about the object to be drawn and reuse that object on multiple draw calls.FCanvasBoxItem
, which we then pass to the DrawItem
function on our Canvas.FCanvasBox
so that it can represent the current value inside the progress bar.18.218.156.35