getUTF8Width に変更

This commit is contained in:
Koichi Ito 2026-09-20 21:02:22 +09:00
parent 2b3b7cfc4e
commit ca05ef14e5
1 changed files with 7 additions and 9 deletions

View File

@ -31,21 +31,16 @@ String replaceMissingGlyphs(const String& text) {
for (size_t index = 0; index < text.length();) { for (size_t index = 0; index < text.length();) {
const uint8_t firstByte = static_cast<uint8_t>(text[index]); const uint8_t firstByte = static_cast<uint8_t>(text[index]);
uint32_t codePoint = 0;
size_t byteCount = 0; size_t byteCount = 0;
// UTF-8の先頭バイトから、1文字のバイト数を判定します。 // UTF-8の先頭バイトから、1文字のバイト数を判定します。
if (firstByte < 0x80) { if (firstByte < 0x80) {
codePoint = firstByte;
byteCount = 1; byteCount = 1;
} else if ((firstByte & 0xE0) == 0xC0 && index + 1 < text.length()) { } else if ((firstByte & 0xE0) == 0xC0 && index + 1 < text.length()) {
codePoint = firstByte & 0x1F;
byteCount = 2; byteCount = 2;
} else if ((firstByte & 0xF0) == 0xE0 && index + 2 < text.length()) { } else if ((firstByte & 0xF0) == 0xE0 && index + 2 < text.length()) {
codePoint = firstByte & 0x0F;
byteCount = 3; byteCount = 3;
} else if ((firstByte & 0xF8) == 0xF0 && index + 3 < text.length()) { } else if ((firstByte & 0xF8) == 0xF0 && index + 3 < text.length()) {
codePoint = firstByte & 0x07;
byteCount = 4; byteCount = 4;
} else { } else {
// 壊れたUTF-8も、表示できない文字としてトーフにします。 // 壊れたUTF-8も、表示できない文字としてトーフにします。
@ -54,7 +49,7 @@ String replaceMissingGlyphs(const String& text) {
continue; continue;
} }
// 2バイト目以降をつなげて、Unicodeの文字コードを作ります。 // 2バイト目以降がUTF-8の続きになっているか確認します。
bool valid = true; bool valid = true;
for (size_t offset = 1; offset < byteCount; ++offset) { for (size_t offset = 1; offset < byteCount; ++offset) {
const uint8_t nextByte = static_cast<uint8_t>(text[index + offset]); const uint8_t nextByte = static_cast<uint8_t>(text[index + offset]);
@ -62,7 +57,6 @@ String replaceMissingGlyphs(const String& text) {
valid = false; valid = false;
break; break;
} }
codePoint = (codePoint << 6) | (nextByte & 0x3F);
} }
if (!valid) { if (!valid) {
@ -71,11 +65,15 @@ String replaceMissingGlyphs(const String& text) {
continue; continue;
} }
// 1文字分のUTF-8文字列を作ります。
String character = text.substring(index, index + byteCount);
// 幅が0なら、その文字の絵がフォントにないと判断します。 // 幅が0なら、その文字の絵がフォントにないと判断します。
if (u8g2.getGlyphWidth(codePoint) == 0) { // getGlyphWidthは使えるU8g2の版が限られるため、getUTF8Widthを使います。
if (u8g2.getUTF8Width(character.c_str()) == 0) {
result += "□"; result += "□";
} else { } else {
result += text.substring(index, index + byteCount); result += character;
} }
index += byteCount; index += byteCount;
} }