master
ブランチ master
ShaderPlayground / deps / imgui / imgui / docs / FONTS.md
31.5 KB、648行 表示 生 Blame 履歴
1_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer)_
2
3## Dear ImGui: Using Fonts
4
5The code in Dear ImGui embeds a copy of [ProggyClean.ttf](https://github.com/bluescan/proggyfonts) by Tristan Grimmer,
6a 13 pixels high, pixel-perfect font used by default. ProggyClean does not scale very nicely.
7
8The code in Dear ImGui embeds a partial copy of [ProggyForever.ttf](https://github.com/ocornut/proggyforever) by Disco Hello & Tristan Grimmer,
9a new font mimicking ProggyClean which does scale nicely.
10
11We embed fonts in the code so you can use Dear ImGui without any file system access.
12If you don't use them you can set `IMGUI_DISABLE_DEFAULT_FONT` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file to ship binaries without the fonts and save about ~26 KB.
13
14Calling io.Fonts->AddFontDefaultVector() loads ProggyForever.
15Calling io.Fonts->AddFontDefaultBitmap() loads ProggyClean.
16Calling io.Fonts->AddFontDefault() selects one based on the expected default font size (when `style.FontSizeBase * style.FontScaleMain * style.FontSizeDpi >= 15` we use ProggyForever).
17
18You may also load external .TTF/.OTF files, see instructions on this page.
19In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience.
20
21**Also read the FAQ:** https://www.dearimgui.com/faq (there is a Fonts section!)
22
23## Index
24- [Troubleshooting](#troubleshooting)
25- [New! Dynamic Fonts system in 1.92 (June 2025)](#new-dynamic-fonts-system-in-192-june-2025)
26- [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application)
27- [Fonts Loading Instructions](#fonts-loading-instructions)
28- [Loading Font Data from Memory](#loading-font-data-from-memory)
29- [Loading Font Data Embedded In Source Code](#loading-font-data-embedded-in-source-code)
30- [Using Icon Fonts](#using-icon-fonts)
31 - [Excluding Overlapping Ranges](#excluding-overlapping-ranges)
32- [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype)
33- [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis)
34- [Using Custom Glyph Ranges](#using-custom-glyph-ranges)
35- [Using Custom Colorful Icons](#using-custom-colorful-icons)
36- [About Filenames](#about-filenames)
37- [About UTF-8 Encoding](#about-utf-8-encoding)
38- [Debug Tools](#debug-tools)
39- [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository)
40- [Font Links](#font-links)
41
42---------------------------------------
43
44## Troubleshooting
45
46**A vast majority of font and text related issues encountered comes from 4 things:**
47
48### (1) Invalid filename due to use of `\` or unexpected working directory.
49
50See [About Filenames](#about-filenames). AddFontXXX() functions should assert if the filename is incorrect.
51
52### (2) Invalid UTF-8 encoding of your non-ASCII strings.
53
54See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to confirm encoding of string literal in your source code is correct.
55
56### (3) Missing glyph ranges.
57
58🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary.**
59
60⏪ Before 1.92: you need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges.
61
62This was a previous constraint of Dear ImGui (lifted in 1.92): when loading a font you need to specify which characters glyphs to load.
63All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. This is generally called by the Renderer backend, e.g. `ImGui_ImplDX11_NewFrame()` calls it. **If you use custom glyphs ranges, make sure the array is persistent** and available during the calls to `GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build()`.
64
65### (4) Font atlas texture fails to upload to GPU.
66
67🆕 **Since 1.92, with an up to date backend: atlas is built incrementally and dynamically resized, this is less likely to happen**
68
69:rewind: This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty white rectangles.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours.
70
71![empty squares](https://github.com/user-attachments/assets/68b50fb5-8b9d-4c38-baec-6ac384f06d26)
72
73Some solutions:
74- You may reduce oversampling, e.g. `font_config.OversampleH = 1`, this will half your texture size for a quality loss.
75 Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample).
76- Reduce glyphs ranges by calculating them from source localization data.
77 You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win!
78- Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two.
79
80### (5) Reduce texture resizes/copy on startup
81
82🆕 Since 1.92, the ImFontAtlas is initially created using a 512x128 texture, then grows as glyphs and fonts are used. Atlas growth leads to alloc+copy, and both the old and new sized textures are present in memory for a short time (typically one frame). If you use known fonts and want to reduce initial growth, you may set `TexMinWidth` and `TexMinHeight` during initializaton.
83
84```cpp
85ImFontAtlas* atlas = io.Fonts;
86atlas->TexMinWidth = 1024;
87atlas->TexMinHeight = 1024;
88atlas->AddFont(...);
89```
90
91##### [Return to Index](#index)
92
93---------------------------------------
94
95## New! Dynamic Fonts system in 1.92 (June 2025)
96
97v1.92 introduces a newer, dynamic font system. It requires backend to support the `ImGuiBackendFlags_HasTextures` feature:
98- Users of icons, Asian and non-English languages do not need to pre-build all glyphs ahead of time. Saving on loading time, memory, and also reducing issues with missing glyphs. Specifying glyph ranges is not needed anymore.
99- `PushFont(NULL, new_size)` may be used anytime to change font size.
100- Packing custom rectangles is more convenient as pixels may be written to immediately.
101- Any update to fonts previously required backend specific calls to re-upload the texture, and said calls were not portable across backends. It is now possible to scale fonts etc. in a way that doesn't require you to make backend-specific calls.
102- It is possible to plug a custom loader/backend to any font source.
103
104See [#8465](https://github.com/ocornut/imgui/issues/8465) for more details.
105
106
107##### [Return to Index](#index)
108
109---------------------------------------
110
111## How should I handle DPI in my application?
112
113Since 1.92, with an updated backend, you can set `style.FontScaleDpi = your_content_scale;` to scale all fonts.
114<BR>You can call `style.ScaleAllSizes(xxx)` at init time or every frame at the beginning of your main loop to scale sizes/paddings.
115<BR>Since 1.92, with an updated backend, macOS style pixel/backing style scale is automatically handled.
116<BR>See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application) for more details.
117
118##### [Return to Index](#index)
119
120---------------------------------------
121
122## Fonts Loading Instructions
123
124**Select base size**
125```cpp
126ImGuiStyle& style = ImGui::GetStyle();
127style.FontSizeBase = 20.0f;
128```
129
130**Load default font:**
131```cpp
132ImGuiIO& io = ImGui::GetIO();
133io.Fonts->AddFontDefaultVector(); // Load embedded scalable font.
134```
135```cpp
136io.Fonts->AddFontDefaultBitmap(); // Load embedded bitmap font (legacy).
137```
138```cpp
139io.Fonts->AddFontDefault(); // Load embedded font (legacy: auto-selected between the two above).
140```
141
142**Load .TTF/.OTF file with:**
143
144🆕 **Since 1.92, with an up to date backend: passing a size is not necessary**
145```cpp
146ImGuiIO& io = ImGui::GetIO();
147io.Fonts->AddFontFromFileTTF("font.ttf");
148```
149:rewind: **Before 1.92, or without an up to date backend:**
150```cpp
151ImGuiIO& io = ImGui::GetIO();
152io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
153```
154If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read [About filenames](#about-filenames) carefully.
155
156**Load multiple fonts:**
157```cpp
158// Init
159ImGuiIO& io = ImGui::GetIO();
160ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf",);
161ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf");
162```
163
164In your application loop, select which font to use:
165```cpp
166ImGui::Text("Hello"); // use the default font (which is the first loaded font)
167ImGui::PushFont(font2, 0.0f); // change font, keep current size
168ImGui::Text("Hello with another font");
169ImGui::PopFont();
170```
171
172**For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):**
173```cpp
174ImFontConfig config;
175config.OversampleH = 1.0f;
176ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);
177```
178
179**Combine multiple fonts into one:**
180
181🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary.**
182```cpp
183// Load a first font
184ImFont* font = io.Fonts->AddFontDefaultVector();
185ImFontConfig config;
186config.MergeMode = true;
187io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 0.0f, &config); // Merge into first font to add e.g. Asian characters
188io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 0.0f, &config); // Merge into first font to add Icons
189```
190:rewind: **Before 1.92, or without an up to date backend:**
191```cpp
192// Load a first font
193ImFont* font = io.Fonts->AddFontDefault();
194
195// Add character ranges and merge into the previous font
196// The ranges array is not copied by the AddFont* functions and is used lazily
197// so ensure it is available at the time of building or calling GetTexDataAsRGBA32().
198static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope.
199ImFontConfig config;
200config.MergeMode = true;
201io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font
202io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font
203io.Fonts->Build();
204```
205
206**Add a fourth parameter to bake specific font ranges only:**
207
208🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. All the GetGlyphRangesXXX() functions are marked obsolete.**
209```cpp
210// Basic Latin, Extended Latin
211io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault());
212
213// Default + Selection of 2500 Ideographs used by Simplified Chinese
214io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
215
216// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
217io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesJapanese());
218```
219See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges.
220
221**Example loading and using a Japanese font:**
222
223🆕 **Since 1.92, with an up to date backend:**
224```cpp
225ImGuiIO& io = ImGui::GetIO();
226io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf");
227```
228
229:rewind: **Before 1.92, or without an up to date backend:**
230```cpp
231ImGuiIO& io = ImGui::GetIO();
232io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
233```
234
235```cpp
236ImGui::Text(u8"こんにちは!テスト %d", 123);
237if (ImGui::Button(u8"ロード"))
238{
239 // do stuff
240}
241ImGui::InputText("string", buf, IM_COUNTOF(buf));
242ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
243```
244
245![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png)
246<br>_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_
247
248##### [Return to Index](#index)
249
250---------------------------------------
251
252## Loading Font Data from Memory
253
254```cpp
255ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, ...);
256```
257
258IMPORTANT: `AddFontFromMemoryTTF()` by default transfer ownership of the data buffer to the font atlas, which will attempt to free it on destruction.
259This was to avoid an unnecessary copy, and is perhaps not a good API (a future version will redesign it).
260If you want to keep ownership of the data and free it yourself, you need to clear the `FontDataOwnedByAtlas` field:
261
262```cpp
263ImFontConfig font_cfg;
264font_cfg.FontDataOwnedByAtlas = false;
265ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg);
266```
267IMPORTANT: Since 1.92, when using `FontDataOwnedByAtlas = false`, font data needs to available until `atlas->RemoveFont()`, or more typically until a shutdown of the owning context or font atlas. It was not immediately noticeable in 1.92.0 due to a bug in handling `FontDataOwnedByAtlas = false`, which was fixed in 1.92.6.
268
269##### [Return to Index](#index)
270
271---------------------------------------
272
273## Loading Font Data Embedded In Source Code
274
275- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code.
276- See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instructions on how to use the tool.
277- You may find a precompiled version binary_to_compressed_c.exe for Windows inside the demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)).
278- The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger.
279
280Then load the font with:
281```cpp
282ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
283```
284or
285```cpp
286ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
287```
288
289##### [Return to Index](#index)
290
291---------------------------------------
292
293## Using Icon Fonts
294
295Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application.
296A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth.
297
298To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders.
299
300So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon.
301
302🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. You can omit this parameter.**
303Example Setup:
304```cpp
305// Merge icons into default tool font
306#include "IconsFontAwesome.h"
307ImGuiIO& io = ImGui::GetIO();
308io.Fonts->AddFontDefaultVector();
309ImFontConfig config;
310config.MergeMode = true;
311config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced
312io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config);
313```
314:rewind: **Before 1.92:**
315```cpp
316// Merge icons into default tool font
317#include "IconsFontAwesome.h"
318ImGuiIO& io = ImGui::GetIO();
319io.Fonts->AddFontDefault();
320
321ImFontConfig config;
322config.MergeMode = true;
323config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced
324static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
325io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges);
326```
327Example Usage:
328```cpp
329// Usage, e.g.
330ImGui::Text("%s among %d items", ICON_FA_SEARCH, count);
331ImGui::Button(ICON_FA_SEARCH " Search");
332// C string _literals_ can be concatenated at compilation time, e.g. "hello" " world"
333// ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB"
334```
335See Links below for other icons fonts and related tools.
336
337**Monospace Icons?**
338
339To make your icon look more monospace and facilitate alignment, you may want to set the `ImFontConfig::GlyphMinAdvanceX` value when loading an icon font.
340If you `GlyphMinAdvanceX` you need to pass a `font_size` to `AddFontXXX()` calls, as the MinAdvanceX value will be specified for the given size and scaled otherwise.
341
342**Screenshot**
343
344Here's an application using icons ("Avoyd", https://www.avoyd.com):
345![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg)
346
347##### [Return to Index](#index)
348
349---------------------------------------
350
351### Excluding Overlapping Ranges
352
353🆕 **Since 1.92, with an up to date backend: glyphs ranges are ignored**: when loading a glyph, input fonts in the merge list are queried in order. The first font which has the glyph loads it.
354<BR>‼️ **If you are merging several fonts, you may have undesirable overlapping ranges.** You can use `ImFontConfig::GlyphExcludeRanges[] `to specify ranges to ignore in a given Input.
355
356```cpp
357// Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range
358static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
359ImFontConfig cfg1;
360cfg1.GlyphExcludeRanges = exclude_ranges;
361io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
362
363// Add Font Source 2, which expects to use the range above
364ImFontConfig cfg2;
365cfg2.MergeMode = true;
366io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2);
367```
368Another (silly) example:
369```cpp
370// Remove 'A'-'Z' from first font
371static ImWchar exclude_ranges[] = { 'A', 'Z', 0 };
372ImFontConfig cfg1;
373cfg1.GlyphExcludeRanges = exclude_ranges;
374io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1);
375
376// Load another font to fill the gaps
377ImFontConfig cfg2;
378cfg2.MergeMode = true;
379io.Fonts->AddFontFromFileTTF("Roboto-Medium.ttf", 0.0f, &cfg2);
380```
381![image](https://github.com/user-attachments/assets/f3d751d3-1aee-4698-bd9b-f511902f56bb)
382
383You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate understanding which font input is providing which glyph.
384
385##### [Return to Index](#index)
386
387---------------------------------------
388
389## Using FreeType Rasterizer (imgui_freetype)
390
391- Dear ImGui uses [stb_truetype.h](https://github.com/nothings/stb/) to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read.
392- You can however use `imgui_freetype.cpp` from the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. Compile with this file and add `#define IMGUI_ENABLE_FREETYPE` to your imconfig.h file or build system to automatically activate it.
393- FreeType supports auto-hinting which tends to improve the readability of small fonts. It makes a big difference especially at smaller resolutions.
394- Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder.
395- Correct sRGB space blending will have an important effect on your font rendering quality.
396
397##### [Return to Index](#index)
398
399---------------------------------------
400
401## Using Colorful Glyphs/Emojis
402
403- Rendering of colored emojis is supported by imgui_freetype with FreeType 2.10+.
404- You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag.
405- Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`.
406- Not all types of color fonts are supported by FreeType at the moment.
407- Stateful Unicode features such as skin tone modifiers are not supported by the text renderer.
408
409![colored glyphs](https://user-images.githubusercontent.com/8225057/106171241-9dc4ba80-6191-11eb-8a69-ca1467b206d1.png)
410
411```cpp
412io.Fonts->AddFontFromFileTTF("../../../imgui_dev/data/fonts/NotoSans-Regular.ttf", 16.0f);
413static ImWchar ranges[] = { 0x1, 0x1FFFF, 0 };
414static ImFontConfig cfg;
415cfg.MergeMode = true;
416cfg.FontLoaderFlags |= ImGuiFreeTypeLoaderFlags_LoadColor;
417io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg);
418```
419
420##### [Return to Index](#index)
421
422---------------------------------------
423
424## Using Custom Glyph Ranges
425
426🆕 **Since 1.92, with an up to date backend: specifying glyph ranges is unnecessary. Therefore this is not really useful any more.**
427
428:rewind: You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs.
429```cpp
430ImVector<ImWchar> ranges;
431ImFontGlyphRangesBuilder builder;
432builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
433builder.AddChar(0x7262); // Add a specific character
434builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
435builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
436
437io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, nullptr, ranges.Data);
438io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted.
439```
440
441##### [Return to Index](#index)
442
443---------------------------------------
444
445## Using Custom Colorful Icons
446
447🆕 **Since 1.92, with an up to date backend: this system has been revamped.**
448
449TL;DR; With the new system, it is recommended that you create a custom `ImFontLoader` and register your fonts with it.
450`AddCustomRectFontGlyph()` has been obsoleted because its API does not make much sense with resizable fonts.
451
452You can ask questions in [#8466](https://github.com/ocornut/imgui/issues/8466).
453
454:rewind: **Before 1.92:**
455
456As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)**
457
458- You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`.
459- You can then use `ImFontAtlas::GetCustomRect(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles.
460- This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale).
461
462#### Pseudo-code:
463```cpp
464// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font
465ImFont* font = io.Fonts->AddFontDefaultVector();
466int rect_ids[2];
467rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1);
468rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1);
469
470// Build atlas
471io.Fonts->Build();
472
473// Retrieve texture in RGBA format
474unsigned char* tex_pixels = nullptr;
475int tex_width, tex_height;
476io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height);
477
478for (int rect_n = 0; rect_n < IM_COUNTOF(rect_ids); rect_n++)
479 if (const ImTextureRect* rect = io.Fonts->GetCustomRect(rect_ids[rect_n]))
480 {
481 // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!)
482 for (int y = 0; y < rect->Height; y++)
483 {
484 ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X);
485 for (int x = rect->Width; x > 0; x--)
486 *p++ = IM_COL32(255, 0, 0, 255);
487 }
488 }
489```
490
491##### [Return to Index](#index)
492
493---------------------------------------
494
495## About Filenames
496
497**Please note that many new C/C++ users have issues loading their files _because the filename they provide is wrong_ due to incorrect assumption of what is the current directory.**
498
499Two things to watch for:
500
501(1) In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful.
502```cpp
503io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!!
504io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT
505```
506In some situations, you may also use `/` path separator under Windows.
507
508(2) Make sure your IDE/debugger settings starts your executable from the right working (current) directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it often starts from the folder where object or executable files are stored.
509```cpp
510io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); // Relative filename depends on your Working Directory when running your program!
511io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); // Load from the parent folder of your Working Directory
512```
513##### [Return to Index](#index)
514
515---------------------------------------
516
517## About UTF-8 Encoding
518
519**For non-ASCII characters display, a common user issue is not passing correctly UTF-8 encoded strings.**
520
521(1) We provide a function `ImGui::DebugTextEncoding(const char* text)` which you can call to verify the content of your UTF-8 strings.
522This is a convenient way to confirm that your encoding is correct.
523
524```cpp
525ImGui::SeparatorText("CORRECT");
526ImGui::DebugTextEncoding(u8"こんにちは");
527
528ImGui::SeparatorText("INCORRECT");
529ImGui::DebugTextEncoding("こんにちは");
530```
531![UTF-8 Encoding viewer](https://github.com/ocornut/imgui/assets/8225057/61c1696a-9a94-46c5-9627-cf91211111f0)
532
533You can also find this tool under `Metrics/Debuggers->Tools->UTF-8 Encoding viewer` if you want to paste from clipboard, but this won't validate the UTF-8 encoding done by your compiler.
534
535(2) To encode in UTF-8:
536
537There are also compiler-specific ways to enforce UTF-8 encoding by default:
538
539- Visual Studio compiler: `/utf-8` command-line flag.
540- Visual Studio compiler: `#pragma execution_character_set("utf-8")` inside your code.
541- Since May 2023 we have changed the Visual Studio projects of all our examples to use `/utf-8` ([see commit](https://github.com/ocornut/imgui/commit/513af1efc9080857bbd10000d98f98f2a0c96803)).
542
543Or, since C++11, you can use the `u8"my text"` syntax to encode literal strings as UTF-8. e.g.:
544```cpp
545ImGui::Text(u8"hello");
546ImGui::Text(u8"こんにちは"); // this will always be encoded as UTF-8
547ImGui::Text("こんにちは"); // the encoding of this is depending on compiler settings/flags and may be incorrect.
548```
549
550Since C++20, because the C++ committee hate its users, they decided to change the `u8""` syntax to not return `const char*` but a new type `const char8_t*` which doesn't cast to `const char*`.
551Because of type usage of `u8""` in C++20 is a little more tedious:
552```cpp
553ImGui::Text((const char*)u8"こんにちは");
554```
555However, you can disable this behavior completely using the compiler option [`/Zc:char8_t-`](https://learn.microsoft.com/en-us/cpp/build/reference/zc-char8-t?view=msvc-170) for MSVC and [`-fno-char8_t`](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1423r3.html) for Clang and GCC.
556##### [Return to Index](#index)
557
558---------------------------------------
559
560## Debug Tools
561
562#### Metrics/Debugger->Fonts
563You can use the `Metrics/Debugger` window (available in `Demo>Tools`) to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`. The same information are also available in the Style Editor under Fonts.
564
565![Fonts debugging](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png)
566
567#### UTF-8 Encoding Viewer**
568You can use the `UTF-8 Encoding viewer` in `Metrics/Debugger` to verify the content of your UTF-8 strings. From C/C++ code, you can call `ImGui::DebugTextEncoding("my string");` function to verify that your UTF-8 encoding is correct.
569
570![UTF-8 Encoding viewer](https://user-images.githubusercontent.com/8225057/166505963-8a0d7899-8ee8-4558-abb2-1ae523dc02f9.png)
571
572##### [Return to Index](#index)
573
574---------------------------------------
575
576## Credits/Licenses For Fonts Included In Repository
577
578Embedded in source code:
579
580**ProggyClean.ttf**, by Tristan Grimmer
581<br>MIT License
582<br>(recommended loading setting: Size = 13.0, GlyphOffset.y = +1, PixelSnapH = true)
583<br>https://github.com/bluescan/proggyfonts
584
585**ProggyForever.ttf**, by Disco Hello, Tristan Grimmer
586<BR>MIT License
587<BR>https://github.com/ocornut/proggyforever
588
589Extra fonts files are available in the `misc/fonts/` folder.
590Compared to 2014 when they were first introduced, we now have better font support and we embed ProggyForever.
591I believe all the files here are unnecessary nowadays. You can find font yourself. They might eventually be removed.
592
593**Roboto-Medium.ttf**, by Christian Robetson
594<br>Apache License 2.0
595<br>https://fonts.google.com/specimen/Roboto
596
597**Cousine-Regular.ttf**, by Steve Matteson
598<br>Digitized data copyright (c) 2010 Google Corporation.
599<br>Licensed under the SIL Open Font License, Version 1.1
600<br>https://fonts.google.com/specimen/Cousine
601
602**DroidSans.ttf**, by Steve Matteson
603<br>Apache License 2.0
604<br>https://www.fontsquirrel.com/fonts/droid-sans
605
606**ProggyTiny.ttf**, by Tristan Grimmer
607<br>MIT License
608<br>(recommended loading setting: Size = 10.0, GlyphOffset.y = +1)
609<br>https://github.com/bluescan/proggyfonts
610
611**Karla-Regular.ttf**, by Jonathan Pinhorn
612<br>SIL OPEN FONT LICENSE Version 1.1
613
614##### [Return to Index](#index)
615
616## Font Links
617
618#### ICON FONTS
619
620- C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders
621- FontAwesome https://fortawesome.github.io/Font-Awesome
622- OpenFontIcons https://github.com/traverseda/OpenFontIcons
623- Google Icon Fonts https://design.google.com/icons/
624- Kenney Icon Font (Game Controller Icons) https://github.com/nicodinh/kenney-icon-font
625- IcoMoon - Custom Icon font builder https://icomoon.io/app
626
627#### REGULAR FONTS
628
629- Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/
630- Open Sans Fonts https://fonts.google.com/specimen/Open+Sans
631- (Japanese) M+ fonts by Coji Morishita http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
632
633#### MONOSPACE FONTS
634
635<img width="1172" height="715" alt="image" src="https://github.com/user-attachments/assets/c9702534-4877-41c9-ae0d-252933c26ced" />
636
637- Proggy Fonts, by Tristan Grimmer https://github.com/bluescan/proggyfonts
638- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font
639- Google Noto Mono Fonts: https://www.google.com/get/noto/
640- Typefaces for source code beautification: https://github.com/chrissimpkins/codeface
641- Programmation fonts: http://s9w.github.io/font_compare/
642- Inconsolata: http://www.levien.com/type/myfonts/inconsolata.html
643- Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro
644- Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/
645
646Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).
647
648##### [Return to Index](#index)