下面是一个使用 GDI+ 的 DrawString 函数输出文本的 C++ 代码示例,并在文本像素长度超过 200 时,从最后一个空格处截断文本,并将剩余部分输出到下一行。

#include <iostream>
#include <windows.h>
#include <gdiplus.h>

using namespace Gdiplus;

int main()
{
    GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdiplusToken;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    HWND hwnd = GetConsoleWindow();
    HDC hdc = GetDC(hwnd);
    Graphics graphics(hdc);

    FontFamily fontFamily(L"Arial");
    Font font(&fontFamily, 12, FontStyleRegular, UnitPixel);
    SolidBrush brush(Color(255, 0, 0, 0));

    std::wstring text = L"This is a long text that needs to be truncated when it exceeds 200 pixels.";
    std::wstring truncatedText;
    std::wstring remainingText;

    RectF rect;
    graphics.MeasureString(text.c_str(), -1, &font, PointF(0, 0), &rect);

    if (rect.Width <= 200)
    {
        graphics.DrawString(text.c_str(), -1, &font, PointF(10, 10), &brush);
    }
    else
    {
        int index = text.rfind(L' ', 200);
        truncatedText = text.substr(0, index);
        remainingText = text.substr(index + 1);

        graphics.DrawString(truncatedText.c_str(), -1, &font, PointF(10, 10), &brush);
        graphics.DrawString(remainingText.c_str(), -1, &font, PointF(10, 30), &brush);
    }

    GdiplusShutdown(gdiplusToken);
    ReleaseDC(hwnd, hdc);

    return 0;
}

此示例代码使用 GDI+ 库来输出文本。它首先测量整个文本的宽度,如果宽度小于等于 200 像素,则直接输出整个文本。否则,它会找到最后一个空格的位置,将文本从该位置处截断为两个部分,第一部分将输出在 (10, 10) 位置,第二部分将输出在 (10, 30) 位置。

请确保在编译时链接 GDI+ 库,可以使用以下命令编译代码:

g++ main.cpp -lgdiplus -mwindows

注意:在使用 GDI+ 之前,需要调用 GdiplusStartup 函数进行初始化,然后在程序结束时调用 GdiplusShutdown 函数进行清理。

C++ GDI+ DrawString 文本截断:像素长度超过 200 时从空格处截断

原文地址: https://www.cveoy.top/t/topic/oNth 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录