C/C++ Imgui gradient text

Snow

Moderator
Apr 14, 2022
35
4
Here's an example of how you could create gradient text using ImGui in C++:

C++:
#include <imgui.h>

void MyImGuiFunction()
{
    // Start a new ImGui window
    ImGui::Begin("My Window");

    // Set up the text parameters
    const char* text = "Gradient Text";
    const ImVec2 textPos = ImGui::GetCursorScreenPos();
    const ImU32 colorStart = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f));
    const ImU32 colorEnd = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 1.0f, 1.0f));

    // Calculate the text size
    const ImFont* font = ImGui::GetFont();
    const float fontSize = ImGui::GetFontSize();
    const ImVec2 textSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, text);

    // Draw the gradient text
    ImDrawList* drawList = ImGui::GetWindowDrawList();
    for (int i = 0; i < strlen(text); i++)
    {
        const char c = text[i];
        const ImVec2 charPos = textPos + ImVec2(i * fontSize, 0.0f);

        const float t = (i + 0.5f) / strlen(text);
        const ImU32 color = ImLerp(colorStart, colorEnd, t);

        drawList->AddText(font, fontSize, charPos, color, &c, &c + 1);
    }

    // End the ImGui window
    ImGui::End();
}

This code creates a new ImGui window and draws text with a gradient color. The text is "Gradient Text", but you can replace it with any other text you want. The gradient color starts at red and ends at blue, but you can customize the start and end colors using ImVec4 color vectors. The gradient color is calculated using the ImLerp function, which linearly interpolates between two ImU32 colors based on a floating-point value between 0.0f and 1.0f.

The text is drawn using the AddText function of the ImDrawList interface. Each character is drawn separately, with its position calculated based on the current text position and the size of the font. The color of each character is calculated based on its position in the text string, using the ImLerp function to interpolate between the start and end colors.

Note that the code assumes that the font size is constant for all characters. If you want to use a variable font size, you'll need to modify the code accordingly.
 
Last edited by a moderator:
Top