Skia Internals 04: Text and Paragraph Layout
字符是 Unicode 码点,glyph 是字体里的形状,绘制只认 glyph。中间的映射叫 shaping,处理连字、字距、双向文本。
SkTextBlob 批量绘制。SkParagraph 管样式、换行、对齐、字体回退,适合富文本。核心 Skia 不做复杂 shaping;它只提供 glyph 与位置。字体回退、缺字、emoji 彩色字体,都是产品必须自己设计的链路。
第 02 章 / 共 13 章
字符是 Unicode 码点,glyph 是字体里的具体形状。一个字可能对应多个 glyph,也可能反过来。绘制时,Skia 只认 glyph,所以中间必须有人做映射。
fi 可能是一个 glyph。AV 的间距要调整。é 可能是 e + 重音两个码点。SkParagraph 负责)。SkTextBlob / drawGlyphs。核心 Skia 只做第 4 步;SkShaper 封装 HarfBuzz,SkParagraph 再封装 shaping + 断行 + 回退。
drawString 画中文/emoji,可能缺字或间距错误。第 04 章 / 共 13 章
本章讲 字体对象。下面把它拆成可复用的机制与代码。
sk_sp<SkTypeface> tf = SkTypeface::MakeFromName(
"Noto Sans CJK SC", SkFontStyle());
SkFont font(tf, 32);
SkRect bounds;
float width = font.measureText(text, len,
SkTextEncoding::kUTF8, &bounds);
SkTextBlob 是不可变的 glyph 批次:
SkTextBlobBuilder builder;
auto run = builder.allocRunPos(font, glyphCount);
// 填充 run.glyphs / run.pos
sk_sp<SkTextBlob> blob = builder.make();
canvas->drawTextBlob(blob, x, y, paint);
SkParagraph 更合适。drawTextBlob(blob, x, y, paint) 的 y 是基线;要按顶边对齐,需减去 font.getMetrics().fAscent。
第 06 章 / 共 13 章
本章讲 SkParagraph。下面把它拆成可复用的机制与代码。
auto provider = sk_make_sp<TypefaceFontProvider>();
provider->registerTypeface(typeface);
auto fc = sk_make_sp<FontCollection>();
fc->setDefaultFontManager(provider);
ParagraphStyle ps;
TextStyle ts;
ts.setColor(SK_ColorWHITE);
ts.setFontSize(32);
ParagraphBuilder builder(ps, fc);
builder.pushStyle(ts);
builder.addText(u8"Skia 的段落排版");
auto paragraph = builder.Build();
paragraph->layout(800);
paragraph->paint(canvas, 40, 80);
字体不可能覆盖所有 Unicode。缺字时,Skia 通过 SkFontMgr 按回退链查找:
SkTypeface 是否包含该字符;SkFontMgr::matchFamilyStyleCharacter);.notdef(豆腐块)。SkFontMgr* mgr = SkFontMgr::RefDefault();
sk_sp<SkTypeface> tf = mgr->matchFamilyStyleCharacter(
"Noto Sans", SkFontStyle(), bcp47, 1, unichar);
bcp47 语言标签选择。.notdef 数量。可变字体用一个文件存多个字重/宽度:
wght:字重(100–900);wdth:宽度(75–125);ital、slnt、opsz 等。SkFontArguments args;
SkFontArguments::VariationPosition::Coordinate coords[] = {
{SkSetFourByteTag('w','g','h','t'), 700},
};
args.setVariationDesignPosition({coords, 1});
sk_sp<SkTypeface> tf = SkTypeface::MakeFromData(data, 0, args);
导出 PDF / 嵌入字体时,只保留用到的 glyph:
第 09 章 / 共 13 章
本章讲 文本性能。下面把它拆成可复用的机制与代码。
第 10 章 / 共 13 章
本章讲 加载字体。下面把它拆成可复用的机制与代码。
sk_sp<SkData> data = SkData::MakeFromFileName(
"assets/Inter.ttf");
sk_sp<SkTypeface> tf = SkTypeface::MakeFromData(
std::move(data));
SkFont font(tf, 28);
canvas->drawString("Hello", 40, 80, font, paint);
第 11 章 / 共 13 章
本章讲 实战:标签。下面把它拆成可复用的机制与代码。
SkRect textBounds;
float w = font.measureText(label, len,
SkTextEncoding::kUTF8, &textBounds);
float padX = 14, padY = 8;
SkRect box = SkRect::MakeXYWH(x, y,
w + padX * 2, -textBounds.top() + padY * 2);
canvas->drawRRect(SkRRect::MakeRectXY(box, 999, 999), bg);
float baseline = y + padY - textBounds.top();
canvas->drawTextBlob(blob, x + padX, baseline, textPaint);
第 12 章 / 共 13 章
本章讲 四个常见坑。下面把它拆成可复用的机制与代码。
第 13 章 / 共 13 章
本章讲 本集小结。下面把它拆成可复用的机制与代码。