vanilladocs
vanillapunch.com
API / core/textshaping

core/textshaping

글자 모양 짓기. (글꼴 얼굴 고르기, 양방향 정렬, 글자 모양 잇기, 글리프 래스터)

  • 원본은 브라우저 Canvas2D 가 이 일을 다 한다. (CSS 글꼴 고르기, 양방향 알고리즘, HarfBuzz 모양 짓기, Skia 래스터) 러스트 판은 같은 순서를 크레이트로 밟는다:
  • 글꼴 얼굴(FontFaceDescriptors): CSS @font-face 처럼 이름 하나 아래에 굵기, 기울기, 글자 범위(unicode-range)가 다른 얼굴을 여럿 둔다. 고르기는 CSS Fonts 의 차례(기울기 → 굵기)를 따르고, 같은 굵기와 기울기의 얼굴들은 글자 범위로 나눠 그린다. 나중에 올린 얼굴이 먼저다.
  • 양방향 정렬: unicode-bidi (UAX #9). 문단 방향은 굽는 쪽이 준다. (원본 canvas.direction)
  • 모양 짓기: rustybuzz (HarfBuzz 를 옮긴 것). 아랍어 글자 잇기, 합자, 커닝, 결합 부호 자리를 브라우저처럼 잡는다. 크롬 HarfBuzzFace::GetScaledFont 처럼 자리 배율을 글자 크기의 16.16 고정 소수로 건다. rustybuzz 0.20.1 에는 배율이 없어 저장소의 third_party/rustybuzz 에 hb_font_set_scale(Face::set_scale)을 더한 판을 둔다. 글꼴 단위 값은 em_scale, 가변 GPOS 델타는 em_scalef 로 그 배율에서 반올림하고, 축 값은 HarfBuzz hb_ot_var_normalize_coords 처럼 정규화한다. 같이 둔 third_party/ttf-parser 는 짝 커닝(PairPos 꼴 1)의 장치 표 기준을 바로잡은 판이다.
  • 래스터: fontdue 의 글리프 번호 래스터. 굵은 얼굴이 없으면 가짜 굵게, 기울인 얼굴이 없으면 가짜 기울임을 글리프마다 입힌다. 색 글리프(sbix, CBDT, COLR)는 colorglyph.rs 가 제 색으로 그린다. 크롬처럼 가짜 기울임은 입히고 가짜 굵게는 입히지 않는다.
  • 이모지 표시: 이름 목록의 얼굴은 색과 상관없이 글리프가 있으면 먼저 쓰고, 운영체제 대체 글꼴 단계에서 VS16(FE0F), Emoji_Presentation 글자, 피부색 조정자, 국기, 키캡, 태그 묶음은 색 글리프를 가진 얼굴을, 그 밖(VS15 포함)은 색이 아닌 얼굴을 먼저 고른다. 이형 선택자가 붙은 묶음은 이름 목록에서도 그 표시에 맞는 얼굴만 받는다. 크롬은 지정한 글꼴에 흑백 ❤ 가 있어도 ❤️ (FE0F) 는 색 이모지 글꼴로, 맨 ❤ 는 지정한 글꼴로 그린다. (맥 크롬에서 Canvas2D 로 확인) 리눅스 크롬 157 은 "16px DejaVu Sans" 의 맨 😀 를 DejaVu Sans 의 흑백 글리프로 그린다. (CI 의 measureText)
  • 가짜 기울임과 가짜 굵게는 Chromium 이 Skia 에 주는 값과 같다: 기울기 1/4 (font_platform_data.cc 의 setSkewX(-SK_Scalar1 / 4)), 굵게는 글자 크기의 1/24 (9px 이하) ~ 1/32 (36px 이상) 두께로 윤곽을 칠해 넓힌다. (Skia SkTextFormatParams.h 의 kStdFakeBoldInterpKeys / Values) 둘 다 전진폭은 그대로다. 가짜 굵게를 쓰는 때는 청한 굵기가 600 이상이고 고른 얼굴이 600 아래일 때다. (Blink kBoldThreshold)
  • 글꼴 바이트는 LoadedFont 가 rustybuzz 얼굴과 함께 든다. (self_cell, 얼굴이 바이트를 빌린다) 등록을 지우고 쓰는 곳이 없어지면 바이트도 돌려준다. 같은 파일의 여러 얼굴(TTC 의 굵기들, 가변 글꼴의 굵기 인스턴스)은 바이트(Rc)를 나눠 든다.
  • TTC 같은 글꼴 모음은 얼굴 번호(face_index)를 골라 읽는다. (find_collection_face_index 가 굵기와 기울기로 고른다)
  • 가변 글꼴(fvar 의 wght 축)은 굵기 인스턴스를 축 값으로 만든다. (create_from_shared_bytes 의 variation_list) 모양 짓기는 rustybuzz 가 축 값을 읽고, 래스터는 fontdue 가 축 값을 읽지 못하고 맥 SFNS 같은 가변 글꼴의 윤곽을 그리지 못해, 가변 글꼴은 skrifa 로 축 값을 건 윤곽을 받아 colorglyph 의 넓이 누적 래스터로 그린다. (크롬도 가변 글꼴의 굵기를 축 값으로 그린다)
  • 광학 크기(opsz 축)와 자간 표(trak): 크롬은 글꼴의 opsz 축을 글자 크기로 건다. (font-optical-sizing 의 처음 값 auto, 맥 font_platform_data_mac.mm 의 FontPlatformDataFromCTFont, 모든 운영체제의 웹 글꼴 font_custom_platform_data.cc. 윈도우, 리눅스 시스템 글꼴에는 걸지 않는다) 모양 짓기는 HarfBuzz 에 ptem 으로 글자 크기를 주어 AAT trak 표의 자간을 더한다. (harfbuzz_face.cc 의 GetScaledFont, 맥은 trak 이 있고 sbix 가 없는 글꼴의 전진폭을 CoreText 대신 HarfBuzz 로 셈한다) 러스트 판도 굽는 크기(원본은 폰트 문자열의 px 를 굽는 배율로 키운다)로 opsz 를 걸고 trak 을 더한다. trak 은 rustybuzz 가 아니라 여기서 HarfBuzz 15 (hb-aat-layout-trak-table.hh) 처럼 더한다. 크기 사이는 반올림하지 않고 곧게 잇고, 표의 처음과 끝 밖은 끝 값이며, 글자 묶음의 첫 글리프 전진폭에만 더한다. STAT 표가 없는 글꼴에는 걸지 않는다. (rustybuzz 0.20 은 글꼴 단위 정수로 반올림하고 표 밖을 늘여 잇고 x_offset 에도 반을 더하고 STAT 을 보지 않는다) 맥 시스템 UI 글꼴(SFNS, opsz 17 ~ 96, 처음 28)이 16px 에서 opsz 17 과 trak -40 단위로 크롬과 같아진다. (색 이모지는 CoreText 의 전진폭 그대로 둔다)
  • 낱말마다 모양 짓기: 크롬 캔버스(platform/fonts/plain_text_node.cc 의 SegmentWord)는 글을 낱말로 나눠 따로 모양 짓는다. 빈칸을 낀 커닝과 합자가 없다. 빈칸(U+0020), 탭, ZWSP 는 하나씩, 한중일 글자와 이모지는 글자마다 따로다. (find_chrome_word_end) 캔버스의 탭, 줄바꿈, 폼 피드, 캐리지 리턴은 빈칸으로 바꾼다.
  • 맥: 글리프를 원본 크롬 맥처럼 CoreText 로 그린다. (platform/desktop/coretextglyph.rs) 색이 아닌 글리프는 크롬 Canvas2D 와 같은 설정의 A8 마스크(글꼴 부드럽게, CoreGraphics 감마 풀기, 글자 색 밝기의 감마 전보정, 1/4 픽셀 서브픽셀 자리)이고, 파일에서 읽은 색 이모지 글꼴(sbix)은 CoreText 색 그림이다. (rasterize_glyph_at) 색 이모지의 전진폭은 CoreText 가 작은 크기에서 키워 그리는 비를 곱하고 정수 픽셀로 반올림한다. (16px 에서 20, 13px 에서 16, 크롬 measureText 와 같다)
  • 윈도우: 색이 아닌 글리프를 크롬 윈도우처럼 DirectWrite 로 그린다. (platform/desktop/directwriteglyph.rs, 스키아 SkScalerContext_DW 의 그레이스케일 A8 과 감마 전보정, 1/4 픽셀 서브픽셀 자리)
  • 리눅스: 크롬 158 리눅스는 글꼴을 FreeType 이 아니라 스키아 Fontations(skrifa)로 그린다. 러스트 판도 skrifa 윤곽에 fontconfig 의 힌팅 단계로 힌팅을 걸고 감마 1.2, 대비 0.2 로 전보정하며 1/4 픽셀 서브픽셀 자리를 쓴다. (rasterize_hinted_outline_mask)

Text shaping. (picking font faces, bidirectional ordering, joining glyph shapes, glyph rasterization)

  • In the original the browser's Canvas2D does all of this. (CSS font selection, the bidirectional algorithm, HarfBuzz shaping, Skia rasterization) The Rust version follows the same sequence with crates:
  • Font faces (FontFaceDescriptors): like CSS @font-face, several faces with different weights, slants and character ranges (unicode-range) sit under one name. Selection follows the CSS Fonts order (slant, then weight), and faces with the same weight and slant are split by character range when drawing. A face added later wins.
  • Bidirectional ordering: unicode-bidi (UAX #9). The paragraph direction is given by the baking side. (original canvas.direction)
  • Shaping: rustybuzz (a port of HarfBuzz). Arabic joining, ligatures, kerning and combining mark placement come out like the browser. Like Chrome's HarfBuzzFace::GetScaledFont, the position scale is set to the font size as a 16.16 fixed-point number. rustybuzz 0.20.1 has no scale, so the repository carries a build of third_party/rustybuzz with hb_font_set_scale (Face::set_scale) added. Font-unit values are rounded from that scale with em_scale, variable GPOS deltas with em_scalef, and axis values are normalized like HarfBuzz hb_ot_var_normalize_coords. The bundled third_party/ttf-parser is a build with the device table base of pair kerning (PairPos format 1) corrected.
  • Rasterization: fontdue's glyph-index rasterization. Faces with no bold get a fake bold, and faces with no italic get a fake italic, applied per glyph. Color glyphs (sbix, CBDT, COLR) are drawn in their own colors by colorglyph.rs. Like Chrome, fake italic is applied and fake bold is not.
  • Emoji presentation: a face in the name list is used first if it has the glyph, regardless of color. In the operating system fallback step, VS16 (FE0F), Emoji_Presentation characters, skin tone modifiers, flags, keycaps and tag sequences pick a face with color glyphs first, and everything else (including VS15) picks a non-color face first. A sequence carrying a variation selector accepts only the face matching that presentation even in the name list. Chrome draws ❤️ (FE0F) with the color emoji font and a bare ❤ with the specified font, even if the specified font has a monochrome ❤. (checked with Canvas2D on Mac Chrome) Linux Chrome 157 draws a bare 😀 in "16px DejaVu Sans" with DejaVu Sans's monochrome glyph. (measureText on CI)
  • Fake italic and fake bold are the same values Chromium gives Skia: slant 1/4 (setSkewX(-SK_Scalar1 / 4) in font_platform_data.cc), and bold widens the outline by painting a stroke of 1/24 (9px and below) to 1/32 (36px and above) of the font size. (kStdFakeBoldInterpKeys / Values in Skia SkTextFormatParams.h) Both leave the advance unchanged. Fake bold applies when the requested weight is 600 or more and the chosen face is below 600. (Blink kBoldThreshold)
  • Font bytes are held by LoadedFont together with the rustybuzz face. (self_cell, the face borrows the bytes) When the registration is removed and nothing uses it, the bytes are given back too. Several faces of the same file (the weights of a TTC, the weight instances of a variable font) share the bytes (Rc).
  • Font collections like TTC are read by choosing a face index (face_index). (find_collection_face_index picks it by weight and slant)
  • Variable fonts (the wght axis of fvar) make weight instances from axis values. (variation_list of create_from_shared_bytes) Shaping reads the axis values in rustybuzz, but fontdue cannot read axis values and cannot draw the outlines of variable fonts like Mac SFNS, so variable fonts take outlines with axis values applied from skrifa and are drawn with colorglyph's area-accumulation raster. (Chrome also draws the weight of a variable font from axis values)
  • Optical size (opsz axis) and the tracking table (trak): Chrome sets the font's opsz axis to the font size. (initial value auto of font-optical-sizing, FontPlatformDataFromCTFont in Mac font_platform_data_mac.mm, font_custom_platform_data.cc for web fonts on every operating system. It is not applied to Windows and Linux system fonts) Shaping gives HarfBuzz the font size as ptem and adds the tracking of the AAT trak table. (GetScaledFont in harfbuzz_face.cc, on Mac the advances of a font that has trak and no sbix are computed by HarfBuzz instead of CoreText) The Rust version also sets opsz with the baking size (the original grows the px of the font string by the baking scale) and adds trak. trak is added here like HarfBuzz 15 (hb-aat-layout-trak-table.hh), not by rustybuzz. Between sizes it joins straight without rounding, outside the start and end of the table it is the end value, and it is added only to the advance of the first glyph of a cluster. It is not applied to fonts with no STAT table. (rustybuzz 0.20 rounds to integer font units, extends past the table, adds half to x_offset too, and does not look at STAT) The Mac system UI font (SFNS, opsz 17 to 96, initial 28) matches Chrome at 16px with opsz 17 and trak -40 units. (color emoji keep CoreText's advance as is)
  • Per-word shaping: the Chrome canvas (SegmentWord in platform/fonts/plain_text_node.cc) splits text into words and shapes each separately. There is no kerning or ligature across a space. Space (U+0020), tab and ZWSP stand alone, and CJK characters and emoji are separate per character. (find_chrome_word_end) Tab, line feed, form feed and carriage return in the canvas are turned into spaces.
  • Mac: glyphs are drawn with CoreText like the original Chrome on Mac. (platform/desktop/coretextglyph.rs) Non-color glyphs are an A8 mask with the same settings as Chrome Canvas2D (font smoothing, undoing CoreGraphics gamma, gamma precorrection by text color luminance, quarter-pixel subpixel positions), and color emoji fonts read from files (sbix) are CoreText color pictures. (rasterize_glyph_at) The advance of color emoji is multiplied by the ratio at which CoreText enlarges them at small sizes and rounded to whole pixels. (20 at 16px, 16 at 13px, same as Chrome measureText)
  • Windows: non-color glyphs are drawn with DirectWrite like Chrome on Windows. (platform/desktop/directwriteglyph.rs, grayscale A8 and gamma precorrection of Skia SkScalerContext_DW, quarter-pixel subpixel positions)
  • Linux: Chrome 158 on Linux draws fonts with Skia Fontations (skrifa), not FreeType. The Rust version also hints skrifa outlines with fontconfig's hinting level, precorrects with gamma 1.2 and contrast 0.2, and uses quarter-pixel subpixel positions. (rasterize_hinted_outline_mask)
예제Example이모지 표시인지 글 표시인지 가리기Tell emoji presentation from text presentation
use vanilla::core::textshaping::is_emoji_presentation;

assert!(is_emoji_presentation("\u{1F600}"));
assert!(is_emoji_presentation("\u{2764}\u{FE0F}"));
assert!(!is_emoji_presentation("\u{2764}"));
assert!(!is_emoji_presentation("\u{1F600}\u{FE0E}"));
assert!(is_emoji_presentation("\u{1F1F0}\u{1F1F7}"));
assert!(!is_emoji_presentation("A"));

SystemFontMeasuretype

소스source

시스템 글꼴 조각 재기. (조각 글, 오른쪽에서 왼쪽인지 → 전진폭 픽셀)

Measures a system font segment. (segment text, whether right to left → advance in pixels)

pub type SystemFontMeasure<'a> = &'a dyn Fn(&str, bool) -> f32

FontFaceDescriptorsstruct traits Clone, Debug, PartialEq, Eq, Default

소스source

글꼴 얼굴 서술자. (원본 FontFace 의 descriptors: weight, style, unicodeRange)

  • 굵기는 범위로 든다. (가변 글꼴 "100 900" 처럼, 한 값이면 처음과 끝이 같다)
  • 글자 범위가 비었으면 모든 글자다.
  • source_key 는 같은 이름 아래에서 얼굴을 가리키는 열쇠다. (보통 파일 경로, 차례 정하기와 지우기에 쓴다)

Font face descriptors. (the original FontFace descriptors: weight, style, unicodeRange)

  • Weight is held as a range. (like a variable font's "100 900", a single value has the same start and end)
  • An empty character range means all characters.
  • source_key is the key that identifies a face under the same name. (usually the file path, used for ordering and removal)
예제ExampleCSS 서술자 글로 만들고 글자 범위 보기Create from CSS descriptor text and check the character range
use vanilla::FontFaceDescriptors;

let font_face_descriptors = FontFaceDescriptors::create_from_css("100 900", "italic", "U+AC00-D7A3");
assert_eq!((font_face_descriptors.minimum_weight, font_face_descriptors.maximum_weight), (100, 900));
assert!(font_face_descriptors.is_italic);
assert!(font_face_descriptors.contains_character('\u{AC00}'));
assert!(!font_face_descriptors.contains_character('A'));
assert!(FontFaceDescriptors::new().contains_character('A'));
assert_eq!(FontFaceDescriptors::create_with_bold(true).minimum_weight, 700);
생성자constructorpub fn new() -> FontFaceDescriptors#0.4.0 부터since 0.4.0소스source

생성. (굵기 400, 기울이지 않음, 모든 글자. 원본 서술자를 주지 않은 FontFace 와 같다)

Creates. (weight 400, not italic, all characters. Same as the original FontFace with no descriptors given)

반환ReturnsFontFaceDescriptors 굵기 400, 기울이지 않음, 모든 글자, 빈 열쇠의 서술자.Descriptors with weight 400, not italic, all characters, and an empty key.

정적staticpub fn create_with_bold(is_bold: bool) -> FontFaceDescriptors#0.4.0 부터since 0.4.0소스source

굵은 얼굴인지로 생성. (굵으면 700, 아니면 400)

Creates from whether the face is bold. (700 if bold, otherwise 400)

is_boldbool
true 면 굵기 700, false 면 400.Weight 700 if true, 400 if false.

반환ReturnsFontFaceDescriptors 서술자. (굵기 밖은 new 와 같다)Descriptors. (everything other than weight is the same as new)

정적staticpub fn create_from_css(weight: &str, style: &str, unicode_range: &str) -> FontFaceDescriptors#0.4.0 부터since 0.4.0소스source

CSS 서술자 글로 생성. (원본 { weight, style, unicodeRange }, 빈 글은 기본값)

  • weight: "400", "bold", "100 900". style: "normal", "italic", "oblique". unicode_range: "U+0000-00FF, U+0131, U+4??"

Creates from CSS descriptor text. (the original { weight, style, unicodeRange }, empty text means the default)

  • weight: "400", "bold", "100 900". style: "normal", "italic", "oblique". unicode_range: "U+0000-00FF, U+0131, U+4??"
weight&str
CSS font-weight 글. (빈 글이나 모르는 글이면 400)CSS font-weight text. (400 for empty or unknown text)
style&str
CSS font-style 글. (italic 이나 oblique 로 시작하면 기울임, 대소문자는 가리지 않는다)CSS font-style text. (italic if it starts with italic or oblique, case-insensitive)
unicode_range&str
CSS unicode-range 글. (빈 글이면 모든 글자)CSS unicode-range text. (all characters for empty text)

반환ReturnsFontFaceDescriptors 서술자. (source_key 는 빈 글)Descriptors. (source_key is empty text)

필드fieldpub minimum_weight: u16#0.4.0 부터since 0.4.0소스source

굵기 범위의 처음. (CSS 굵기 1 ~ 1000, 기본 400)

Start of the weight range. (CSS weight 1 ~ 1000, default 400)

반환Returnsu16

필드fieldpub maximum_weight: u16#0.4.0 부터since 0.4.0소스source

굵기 범위의 끝. (한 값이면 minimum_weight 와 같다)

End of the weight range. (same as minimum_weight for a single value)

반환Returnsu16

필드fieldpub is_italic: bool#0.4.0 부터since 0.4.0소스source

기울인 얼굴인지.

Whether it is an italic face.

반환Returnsbool

필드fieldpub unicode_range_list: Vec<(u32, u32)>#0.4.0 부터since 0.4.0소스source

글자 범위 목록. ((처음, 끝) 코드 포인트, 끝 포함. 비었으면 모든 글자)

List of character ranges. ((start, end) code points, end inclusive. Empty means all characters)

반환ReturnsVec<(u32, u32)>

필드fieldpub source_key: String#0.4.0 부터since 0.4.0소스source

얼굴 열쇠. (기본 빈 글)

Face key. (empty text by default)

반환ReturnsString

필드fieldpub is_system_fallback: bool#0.4.0 부터since 0.4.0소스source

운영체제가 고른 대체 글꼴의 얼굴인지. (대체 폰트와 마지막 대체 글꼴도, 글자마다 이름 목록의 얼굴을 다 본 뒤에 보는 대체 단계, 이모지 표시는 이 단계에서 색 글리프 얼굴을 먼저 고른다. 기본 false)

Whether this is a face of a fallback font chosen by the operating system. (also fallback fonts and the last resort font; the fallback stage looked at after all faces of the name list for each character, where emoji presentation picks a color glyph face first. Default false)

반환Returnsbool

메서드methodpub fn set_weight(&mut self, weight: u16)#0.4.0 부터since 0.4.0소스source

굵기 한 값 설정.

Sets a single weight value.

weightu16
굵기. (처음과 끝을 이 값으로)Weight. (sets both start and end to this value)
메서드methodpub fn set_weight_from_css(&mut self, weight: &str)#0.4.0 부터since 0.4.0소스source

CSS 굵기 글로 설정. ("normal", "bold", "500", "100 900", 모르는 글은 그대로 둔다)

Sets from CSS weight text. ("normal", "bold", "500", "100 900", unknown text leaves it unchanged)

weight&str
CSS 굵기 글. (빈칸으로 나눈 값이 하나면 그 값, 둘 이상이면 앞의 둘로 범위)CSS weight text. (one value if splitting by spaces gives one, a range from the first two if two or more)
메서드methodpub fn contains_character(&self, character: char) -> bool#0.4.0 부터since 0.4.0소스source

글자가 글자 범위에 드는지. (범위가 비었으면 늘 든다)

Whether a character is in the character range. (always in if the range is empty)

characterchar
볼 글자.Character to check.

반환Returnsbool 범위에 들면 true.true if in the range.

메서드methodpub fn contains_any_character(&self, text: &str) -> bool#0.4.0 부터since 0.4.0소스source

글에 글자 범위에 드는 글자가 있는지.

Whether the text has a character in the character range.

text&str
볼 글.Text to check.

반환Returnsbool 범위에 드는 글자가 하나라도 있으면 true. (빈 글은 false)true if at least one character is in the range. (false for empty text)

LoadedFontstruct

소스source

읽은 글꼴 하나. (래스터용 fontdue, 모양 짓기용 rustybuzz 얼굴과 그 바이트, 색 글리프 표가 있는지)

One loaded font. (fontdue for rasterization, the rustybuzz face for shaping and its bytes, whether it has color glyph tables)

예제Example글꼴 바이트 읽기Read font bytes
use vanilla::core::textshaping::LoadedFont;
use vanilla::platform::find_fallback_font_file;

assert!(LoadedFont::create_from_bytes(vec![0, 1, 2, 3]).is_err());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font");
	assert!(font.has_character('A'));
	assert!(font.units_per_em > 0.0);
	assert_eq!(font.get_face_index(), 0);
	assert!(!font.is_variation_applied());
}
정적staticpub fn create_from_bytes(font_bytes: Vec<u8>) -> Result<LoadedFont, String>#0.4.0 부터since 0.4.0소스source

풀린 글꼴 바이트(ttf, otf, ttc)로 읽기. (모음이면 0 번 얼굴)

Reads from decompressed font bytes (ttf, otf, ttc). (face 0 for a collection)

font_bytesVec<u8>
글꼴 바이트. (WOFF, WOFF2 는 풀어서 줘야 한다)Font bytes. (WOFF and WOFF2 must be decompressed first)

반환ReturnsResult<LoadedFont, String> 읽은 글꼴. 읽지 못하면 Err(까닭).The loaded font. Err(reason) if it cannot be read.

정적staticpub fn create_from_shared_bytes(font_bytes: Rc<[u8]>, face_index: u32, variation_list: &[rustybuzz::Variation]) -> Result<LoadedFont, String>#0.4.0 부터since 0.4.0소스source

나눠 든 바이트의 얼굴 하나 읽기. (모음 안의 얼굴 번호, 가변 글꼴의 축 값)

Reads one face from shared bytes. (face index inside a collection, axis values of a variable font)

font_bytesRc<[u8]>
나눠 드는 글꼴 바이트.Shared font bytes.
face_indexu32
모음 안의 얼굴 번호. (모음이 아니면 0)Face index inside the collection. (0 if not a collection)
variation_list&[rustybuzz::Variation]
걸 축 값. (비었으면 기본 인스턴스)Axis values to apply. (the default instance if empty)

반환ReturnsResult<LoadedFont, String> 읽은 글꼴. 읽지 못하거나 그 번호의 얼굴이 없으면 Err(까닭).The loaded font. Err(reason) if it cannot be read or there is no face with that index.

필드fieldpub raster_font: fontdue::Font#0.4.0 부터since 0.4.0소스source

래스터용 fontdue 글꼴.

fontdue font for rasterization.

반환Returnsfontdue::Font

필드fieldpub units_per_em: f32#0.4.0 부터since 0.4.0소스source

글꼴 단위의 em 크기. (head 표의 unitsPerEm)

Em size in font units. (unitsPerEm of the head table)

반환Returnsf32

필드fieldpub has_color_tables: bool#0.4.0 부터since 0.4.0소스source

색 글리프 표(sbix, CBDT, COLR)가 있는지.

Whether it has color glyph tables (sbix, CBDT, COLR).

반환Returnsbool

메서드methodpub fn read_horizontal_tracking(&self, ptem: f32) -> f32#0.4.0 부터since 0.4.0소스source

trak 표의 가로 자간. (글꼴 단위, ptem 은 글자 크기 픽셀. 표나 STAT 표가 없거나 맥 색 이모지면 0. HarfBuzz 15 의 TrackData::get_tracking 에서 track 0)

  • 크기: 표의 크기 사이는 곧게 잇고, 처음보다 작으면 첫 값, 끝보다 크면 끝 값.
  • track: 0 과 같은 줄이 있으면 그 줄, 없으면 0 을 사이에 둔 두 줄을 곧게 잇는다.

Horizontal tracking from the trak table. (font units, ptem is the font size in pixels. 0 if there is no table or STAT table, or for Mac color emoji. track 0 of TrackData::get_tracking in HarfBuzz 15)

  • Size: interpolated linearly between the table's sizes, the first value if smaller than the first, the last value if larger than the last.
  • track: the row equal to 0 if there is one, otherwise linear interpolation between the two rows around 0.
ptemf32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsf32 자간. (글꼴 단위)Tracking. (font units)

메서드methodpub fn with_optical_sizing_auto(mut self, is_optical_sizing_auto: bool) -> LoadedFont#0.4.0 부터since 0.4.0소스source

opsz 축을 글자 크기로 걸지 정하기. (처음은 건다. 크롬은 윈도우와 리눅스의 시스템 글꼴에는 걸지 않는다)

Sets whether to apply the opsz axis from the font size. (applied initially. Chrome does not apply it to system fonts on Windows and Linux)

is_optical_sizing_autobool
true 면 건다.true to apply it.

반환ReturnsLoadedFont 바꾼 글꼴.The changed font.

메서드methodpub fn read_optical_size(&self, pixel_size: f32) -> Option<f32>#0.4.0 부터since 0.4.0소스source

글자 크기에 거는 opsz 축 값. (축이 있고 거는 글꼴이면 크기를 축 범위로 자른 값, 아니면 None)

opsz axis value applied for the font size. (the size clamped to the axis range if the axis exists and the font applies it, otherwise None)

pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환ReturnsOption<f32> 축 값. opsz 축이 없거나 걸지 않기로 한 글꼴이면 None.Axis value. None if there is no opsz axis or the font is set not to apply it.

메서드methodpub fn create_sized_shaping_face(&self, pixel_size: f32) -> rustybuzz::Face<'_>#0.4.0 부터since 0.4.0소스source

글자 크기의 모양 짓기 얼굴. (opsz 축을 건다. trak 자간은 shape_text 가 따로 더하므로 rustybuzz 의 ptem 은 두지 않는다)

Shaping face for the font size. (applies the opsz axis. trak tracking is added separately by shape_text, so rustybuzz's ptem is not set)

pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsrustybuzz::Face<'_> 모양 짓기 얼굴의 사본. (opsz 를 걸지 않는 글꼴이면 그대로)Copy of the shaping face. (unchanged for a font that does not apply opsz)

메서드methodpub fn with_source_path(mut self, source_path: std::path::PathBuf) -> LoadedFont#0.4.0 부터since 0.4.0소스source

글꼴 파일 경로 적기. (파일에서 읽은 글꼴. 맥은 색 이모지와 윤곽 표가 없는 글꼴을 CoreText 로 그리게 한다)

Records the font file path. (a font read from a file. On Mac, color emoji and fonts without outline tables are drawn with CoreText)

source_pathstd::path::PathBuf
글꼴 파일 경로.Font file path.

반환ReturnsLoadedFont 경로를 적은 글꼴.The font with the path recorded.

메서드methodpub fn is_core_text_raster(&self) -> bool#0.4.0 부터since 0.4.0소스source

맥 CoreText 로 그리는지.

Whether it is drawn with Mac CoreText.

반환Returnsbool CoreText 로 그리면 true. (맥 밖은 늘 false)true if drawn with CoreText. (always false outside Mac)

메서드methodpub fn read_advance_scale(&self, pixel_size: f32) -> f32#0.4.0 부터since 0.4.0소스source

모양 짓기 전진폭에 곱할 비. (맥 색 이모지는 CoreText 가 작은 크기에서 키워 그리는 비, 그 밖은 1)

Ratio to multiply the shaping advance by. (for Mac color emoji, the ratio CoreText enlarges drawing at small sizes, otherwise 1)

pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsf32 비. (맥 색 이모지 밖은 1)Ratio. (1 except for Mac color emoji)

메서드methodpub fn is_bitmap_only_font(&self) -> bool#0.4.0 부터since 0.4.0소스source

비트맵 그림만 있는 색 글꼴인지. (CBDT 나 sbix 가 있고 윤곽 표(glyf, CFF, CFF2)가 없는 글꼴, 맥 CoreText 로 그리는 글꼴은 아니다)

  • 크롬 리눅스(FreeType 과 스키아)처럼 전진폭과 픽셀 상자를 판의 글리프 수치와 그림 상자로 셈한다. (colorglyph::read_bitmap_glyph_advance, read_bitmap_glyph_bounds)

Whether this is a color font with only bitmap images. (a font with CBDT or sbix and no outline table (glyf, CFF, CFF2), not drawn with CoreText on Mac)

  • Like Chrome on Linux (FreeType and Skia), the advance and pixel box come from the strike's glyph metrics and image box. (colorglyph::read_bitmap_glyph_advance, read_bitmap_glyph_bounds)

반환Returnsbool 비트맵만 있으면 true.true if it has only bitmaps.

메서드methodpub fn is_integer_advance(&self) -> bool#0.4.0 부터since 0.4.0소스source

전진폭을 정수 픽셀로 반올림하는지. (맥 색 이모지, 크롬 measureText 가 13px 에서 16, 17px 에서 21 처럼 정수를 준다)

Whether the advance is rounded to integer pixels. (Mac color emoji, Chrome measureText gives integers like 16 at 13px and 21 at 17px)

반환Returnsbool 반올림하면 true. (CoreText 로 그리는 맥 색 이모지만)true if rounded. (only Mac color emoji drawn with CoreText)

메서드methodpub fn get_shaping_face(&self) -> &rustybuzz::Face<'_>#0.4.0 부터since 0.4.0소스source

모양 짓기 얼굴. (축 값을 건 얼굴, 글꼴 표도 이것으로 읽는다)

Shaping face. (the face with axis values applied, font tables are also read through it)

반환Returns&rustybuzz::Face<'_> rustybuzz 얼굴.rustybuzz face.

메서드methodpub fn calculate_normal_line_height(&self, pixel_size: f32) -> f32#0.4.0 부터since 0.4.0소스source

CSS line-height normal 의 줄 높이. (크롬 SimpleFontData::PlatformInit 의 LineSpacing)

  • 크롬은 Skia 가 주는 위아래 길이(fAscent, fDescent)를 각각 반올림하고(FontMetrics::AscentDescentWithHacks), 줄 높이는 lroundf(위) + lroundf(아래) + lroundf(줄 사이 fLeading)다.
  • Skia 가 읽는 표는 운영체제마다 다르다.
  • 리눅스(SkFontHost_FreeType.cpp): OS/2 의 USE_TYPO_METRICS 가 켜져 있으면 typo 값, 아니면 FreeType 의 hhea 값(hhea 가 0 이면 typo, 그것도 0 이면 win 값). ttf-parser 의 ascender, descender, line_gap 이 이 차례로 읽는다.
  • 맥(CoreText): USE_TYPO_METRICS 를 보지 않고 hhea 값이다. (헤드리스 크롬 맥에서 그 비트를 켠 글꼴의 줄 높이가 그대로인 것으로 확인)
  • 윈도우(DirectWrite 의 DWRITE_FONT_METRICS): USE_TYPO_METRICS 면 typo 값, 아니면 win 값과 hhea 줄 높이가 win 높이를 넘는 만큼의 줄 사이로 본다. (DirectWrite 는 고르는 표를 밝히지 않아, 글꼴 세로 수치 안내에 알려진 셈을 쓴다)
  • 맥 크롬은 Times, Helvetica, Courier 의 위 길이에 (위 + 아래) 의 15% 를 반올림해 더한다. (사파리의 SimpleFontDataMac 과 맞춘 값)

Line height of CSS line-height normal. (LineSpacing of Chrome SimpleFontData::PlatformInit)

  • Chrome rounds the ascent and descent from Skia (fAscent, fDescent) separately (FontMetrics::AscentDescentWithHacks), and the line height is lroundf(ascent) + lroundf(descent) + lroundf(line gap fLeading).
  • The tables Skia reads differ by operating system.
  • Linux (SkFontHost_FreeType.cpp): the typo values if USE_TYPO_METRICS in OS/2 is set, otherwise FreeType's hhea values (typo if hhea is 0, the win values if that is also 0). ttf-parser's ascender, descender, line_gap read them in this order.
  • macOS (CoreText): the hhea values, ignoring USE_TYPO_METRICS. (confirmed in headless Chrome on macOS: a font with that bit set keeps the same line height)
  • Windows (DirectWrite's DWRITE_FONT_METRICS): the typo values if USE_TYPO_METRICS, otherwise the win values with a line gap equal to how much the hhea line height exceeds the win height. (DirectWrite does not disclose which table it picks, so the calculation known from font vertical metrics guides is used)
  • Chrome on macOS adds 15% of (ascent + descent), rounded, to the ascent of Times, Helvetica and Courier. (a value matched to Safari's SimpleFontDataMac)
pixel_sizef32
글자 크기. (px)Font size. (px)

반환Returnsf32 줄 높이. (px, 정수)Line height. (px, integer)

메서드methodpub fn calculate_font_bounding_box(&self, pixel_size: f32) -> (f32, f32)#0.4.0 부터since 0.4.0소스source

캔버스의 글꼴 위아래 길이. (크롬 FontMetrics::AscentDescentWithHacks 에 캔버스가 켜는 subpixel_ascent_descent 를 준 값, TextMetrics 의 fontBoundingBoxAscent, fontBoundingBoxDescent)

  • 운영체제마다 읽는 표는 calculate_normal_line_height 와 같다.
  • 위아래 길이를 각각 반올림한다. 위가 3px 보다 작거나 위 + 아래가 2px 보다 작은 작은 글꼴은 반올림하지 않는다. (crbug.com/338908, 글자 기준선 종류마다 기준선이 같아지지 않게)
  • 맥은 Times, Helvetica, Courier 의 위 길이에 (위 + 아래) 의 15% 를 반올림해 더한다.
  • 리눅스의 VDMX 표와 서브픽셀 자리의 아래 길이 빌리기는 FreeType 바이트코드 힌팅(full, normal)과 서브픽셀 자리를 켰을 때만이라, 크롬 리눅스 기본(slight 힌팅, 서브픽셀 자리 꺼짐)처럼 보지 않는다.

Font ascent and descent for the canvas. (Chrome's FontMetrics::AscentDescentWithHacks with the subpixel_ascent_descent the canvas turns on; TextMetrics fontBoundingBoxAscent, fontBoundingBoxDescent)

  • The table read on each operating system is the same as calculate_normal_line_height.
  • Ascent and descent are each rounded. Tiny fonts whose ascent is below 3px or whose ascent + descent is below 2px are not rounded. (crbug.com/338908, so that baselines of different kinds do not coincide)
  • On Mac, 15% of (ascent + descent), rounded, is added to the ascent of Times, Helvetica and Courier.
  • Linux's VDMX table and borrowing descent for subpixel positioning apply only with FreeType bytecode hinting (full, normal) and subpixel positioning, so like Chrome's Linux default (slight hinting, subpixel positioning off) they are not used.
pixel_sizef32
글자 크기. (px)Font size. (px)

반환Returns(f32, f32) (위 길이, 아래 길이). (px, 둘 다 양수, 글자 크기가 0 이면 둘 다 0)(ascent, descent). (px, both positive, both 0 if the font size is 0)

메서드methodpub fn get_font_bytes(&self) -> &Rc<[u8]>#0.4.0 부터since 0.4.0소스source

글꼴 바이트. (같은 파일의 다른 얼굴이 나눠 든다)

Font bytes. (shared with other faces from the same file)

반환Returns&Rc<[u8]> 글꼴 바이트.Font bytes.

메서드methodpub fn get_face_index(&self) -> u32#0.4.0 부터since 0.4.0소스source

글꼴 모음 안의 얼굴 번호.

Face index inside the font collection.

반환Returnsu32 얼굴 번호. (모음이 아니면 0)Face index. (0 if not a collection)

메서드methodpub fn is_variation_applied(&self) -> bool#0.4.0 부터since 0.4.0소스source

축 값을 건 가변 글꼴 인스턴스인지.

Whether it is a variable font instance with axis values applied.

반환Returnsbool 축 값을 걸었으면 true.true if axis values are applied.

메서드methodpub fn is_outline_raster(&self) -> bool#0.4.0 부터since 0.4.0소스source

글리프를 윤곽에서 직접 그리는지. (가변 글꼴. fontdue 는 축 값을 읽지 못하고 맥 SFNS 같은 가변 글꼴의 윤곽을 그리지 못한다)

Whether glyphs are drawn directly from outlines. (variable fonts. fontdue cannot read axis values and cannot draw the outlines of variable fonts like Mac SFNS)

반환Returnsbool 가변 글꼴이거나 축 값을 걸었으면 true.true if it is a variable font or axis values are applied.

메서드methodpub fn read_glyph_metrics(&self, glyph_index: u16, pixel_size: f32) -> (i32, i32, i32, i32)#0.4.0 부터since 0.4.0소스source

글리프가 덮는 픽셀 상자. (펜 원점에서 왼쪽, 아래, 너비, 높이. fontdue Metrics 의 xmin, ymin, width, height 와 같은 뜻, 비었으면 너비와 높이가 0)

Pixel box a glyph covers. (left, bottom, width, height from the pen origin. Same meaning as xmin, ymin, width, height in fontdue Metrics, width and height 0 if empty)

glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returns(i32, i32, i32, i32) (왼쪽, 아래, 너비, 높이). (픽셀, 위가 양수)(left, bottom, width, height). (pixels, up is positive)

메서드methodpub fn read_glyph_path_bounds(&self, glyph_index: u16, pixel_size: f32, skew: f32) -> Option<(f32, f32, f32, f32)>#0.4.0 부터since 0.4.0소스source

measureText 의 닿는 상자에 쓰는 글리프 상자. (맥 크롬처럼 윤곽 경로의 상자, 블링크 skia_text_metrics.cc 의 SkFontGetBoundsForGlyph 가 맥에서 부르는 GetPathBoundsForGlyph. 경로는 CoreText 윤곽(CTFontCreatePathForGlyph)이고 상자는 곡선 조절점까지 넣은 SkPath::getBounds 다)

  • 윤곽 표(glyf, CFF, CFF2)의 점(곡선 조절점 포함)을 그 크기의 축 값으로 읽은 상자를 픽셀로 줄인다. 반올림하지 않는다.
  • 윤곽을 엔진이 읽지 못하는 글꼴(색 이모지 sbix, 윤곽 표가 없는 hvgl 같은)과 윤곽이 빈 글리프는 None 이다. (크롬도 경로가 없으면 정수 상자 getBounds 다)

Glyph bounds used for the measureText bounding box. (the outline path bounds like Mac Chrome: GetPathBoundsForGlyph, which Blink skia_text_metrics.cc SkFontGetBoundsForGlyph calls on Mac. The path is the CoreText outline (CTFontCreatePathForGlyph) and the bounds are SkPath::getBounds including curve control points)

  • Reads the points of the outline table (glyf, CFF, CFF2), including curve control points, with the axis values for that size, and scales the bounds to pixels. No rounding.
  • Fonts whose outlines the engine cannot read (color emoji sbix, hvgl without an outline table, and the like) and glyphs with an empty outline are None. (Chrome also uses the integer getBounds when there is no path)
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
skewf32
가로 기울임. (x 에 y x skew 를 더한다, 가짜 기울임은 SYNTHETIC_ITALIC_SKEW, 아니면 0. 크롬처럼 경로의 점을 기울인 뒤 상자를 잰다)Horizontal skew. (adds y x skew to x; SYNTHETIC_ITALIC_SKEW for fake italic, otherwise 0. Like Chrome, the bounds are measured after skewing the path points)

반환ReturnsOption<(f32, f32, f32, f32)> (왼쪽, 아래, 오른쪽, 위). (펜 원점에서 픽셀, 위가 양수)(left, bottom, right, top). (pixels from the pen origin, up is positive)

메서드methodpub fn read_glyph_skia_bounds(&self, glyph_index: u16, pixel_size: f32, skew: f32) -> Option<(f32, f32, f32, f32)>#0.4.0 부터since 0.4.0소스source

measureText 의 닿는 상자에 쓰는 경로 없는 글리프(맥 색 이모지 같은 CoreText 래스터 글꼴)의 정수 상자. (스키아 getBounds 와 같은 셈, 맥이 아니거나 CoreText 래스터 글꼴이 아니면 None)

  • 스키아 SkScalerContext_Mac::generateMetrics: 스키아가 지은 CTFont 의 상자를 바깥 정수로 넓히고 사방 1 픽셀 더 넓힌다(outset(1, 1)). 가짜 기울임이면 상자를 기울인 뒤 넓힌다.

Integer bounds of a glyph without a path (a CoreText raster font such as Mac color emoji) used for the measureText bounding box. (the same calculation as Skia getBounds; None when not on Mac or not a CoreText raster font)

  • Skia SkScalerContext_Mac::generateMetrics: expands the bounds of the CTFont Skia builds outward to integers and then by 1 pixel on every side (outset(1, 1)). For fake italic, the bounds are skewed before expanding.
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
skewf32
가로 기울임. (x 에 y x skew 를 더한다, 가짜 기울임이 아니면 0)Horizontal skew. (adds y x skew to x; 0 unless fake italic)

반환ReturnsOption<(f32, f32, f32, f32)> (왼쪽, 아래, 오른쪽, 위). (펜 원점에서 픽셀, 위가 양수)(left, bottom, right, top). (pixels from the pen origin, up is positive)

메서드methodpub fn draw_glyph_outline(&self, glyph_index: u16, pixel_size: f32, outline_builder: &mut dyn rustybuzz::ttf_parser::OutlineBuilder) -> bool#0.4.0 부터since 0.4.0소스source

글리프 윤곽 그리기. (글꼴 단위, 그 글자 크기의 축 값(opsz 포함)을 건 윤곽. 가변 글꼴은 skrifa 로, 아니면 ttf-parser 로. 윤곽이 없으면 false)

  • ttf-parser 는 글리프마다 변형이 32 개를 넘는 가변 글꼴(맥 SFNS 같은)의 윤곽을 읽지 못한다.

Draws a glyph outline. (font units, the outline with the axis values (including opsz) for that font size. Variable fonts through skrifa, otherwise through ttf-parser. false if there is no outline)

  • ttf-parser cannot read the outlines of variable fonts with more than 32 variations per glyph (like Mac SFNS).
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀, 가변 글꼴의 opsz 축 값을 고르는 데만 쓴다)Font size. (pixels, used only to pick the opsz axis value of a variable font)
outline_builder&mut dyn rustybuzz::ttf_parser::OutlineBuilder
윤곽을 받을 쪽.Receiver of the outline.

반환Returnsbool 윤곽을 그렸으면 true.true if the outline was drawn.

메서드methodpub fn has_character(&self, character: char) -> bool#0.4.0 부터since 0.4.0소스source

글자를 가졌는지.

Whether it has the character.

characterchar
볼 글자.Character to check.

반환Returnsbool 글리프가 있으면 true.true if there is a glyph.

메서드methodpub fn has_color_character(&self, character: char) -> bool#0.4.0 부터since 0.4.0소스source

글자를 색 글리프로 가졌는지. (sbix, CBDT, COLR)

Whether it has the character as a color glyph. (sbix, CBDT, COLR)

characterchar
볼 글자.Character to check.

반환Returnsbool 색 글리프가 있으면 true. (색 글리프 표가 없는 글꼴은 늘 false)true if there is a color glyph. (always false for fonts without color glyph tables)

RegisteredFontFacestruct traits Clone

소스source

등록된 글꼴 얼굴 하나.

One registered font face.

예제Example보통과 굵은 얼굴 가운데 굵게 고르기Pick bold between a regular and a bold face
use std::rc::Rc;
use vanilla::core::textshaping::{select_font_faces, LoadedFont, RegisteredFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::FontFaceDescriptors;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font"));
	let regular_face = RegisteredFontFace {
		descriptors: FontFaceDescriptors::create_with_bold(false),
		font: font.clone(),
		order_number: 1,
	};
	let bold_face = RegisteredFontFace {
		descriptors: FontFaceDescriptors::create_with_bold(true),
		font,
		order_number: 2,
	};
	let mut resolved_face_list = Vec::new();
	select_font_faces(&[&regular_face, &bold_face], 700, false, &mut resolved_face_list);
	assert_eq!(resolved_face_list.len(), 1);
	assert_eq!(resolved_face_list[0].descriptors.minimum_weight, 700);
	assert!(!resolved_face_list[0].is_synthetic_bold);
}
필드fieldpub descriptors: FontFaceDescriptors#0.4.0 부터since 0.4.0소스source

얼굴 서술자.

Face descriptors.

반환ReturnsFontFaceDescriptors

필드fieldpub font: Rc<LoadedFont>#0.4.0 부터since 0.4.0소스source

읽은 글꼴. (같은 글꼴을 여러 얼굴이 나눠 들 수 있다)

The loaded font. (several faces can share the same font)

반환ReturnsRc<LoadedFont>

필드fieldpub order_number: u64#0.4.0 부터since 0.4.0소스source

올린 차례. (클수록 나중, 나중 것이 먼저 그린다)

Load order. (larger is later, later ones draw first)

반환Returnsu64

ResolvedFontFacestruct traits Clone

소스source

그릴 때 고른 얼굴 하나. (가짜 굵게, 가짜 기울임을 입힐지 함께 든다)

One face chosen for drawing. (also holds whether to apply fake bold and fake italic)

예제Example가짜 기울임은 전진폭을 바꾸지 않는다Fake italic does not change the advance
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font"));
	let upright_face = ResolvedFontFace {
		font: font.clone(),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let italic_face = ResolvedFontFace {
		is_synthetic_italic: true,
		..upright_face.clone()
	};
	let upright_text = shape_text(&[upright_face], "Hello", 20.0, ShapingDirection::LeftToRight, None);
	let italic_text = shape_text(&[italic_face], "Hello", 20.0, ShapingDirection::LeftToRight, None);
	assert_eq!(upright_text.advance_width, italic_text.advance_width);
}
필드fieldpub font: Rc<LoadedFont>#0.4.0 부터since 0.4.0소스source

읽은 글꼴.

The loaded font.

반환ReturnsRc<LoadedFont>

필드fieldpub descriptors: FontFaceDescriptors#0.4.0 부터since 0.4.0소스source

얼굴 서술자.

Face descriptors.

반환ReturnsFontFaceDescriptors

필드fieldpub is_synthetic_bold: bool#0.4.0 부터since 0.4.0소스source

가짜 굵게를 입힐지. (청한 굵기가 600 이상이고 얼굴 굵기가 600 아래)

Whether to apply fake bold. (the requested weight is 600 or more and the face weight is below 600)

반환Returnsbool

필드fieldpub is_synthetic_italic: bool#0.4.0 부터since 0.4.0소스source

가짜 기울임을 입힐지. (기울임을 청했는데 바른 얼굴)

Whether to apply fake italic. (italic was requested but the face is upright)

반환Returnsbool

ShapedGlyphstruct traits Clone, Copy, Debug

소스source

모양 지은 글리프 하나. (길이 단위는 픽셀, y 는 위가 양수)

One shaped glyph. (length unit is pixels, y up is positive)

예제Example글리프는 왼쪽부터 놓인다Glyphs are placed from the left
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face_list = vec![ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	}];
	let shaped_text = shape_text(&face_list, "ab", 20.0, ShapingDirection::LeftToRight, None);
	let first_glyph = shaped_text.glyph_list[0];
	let second_glyph = shaped_text.glyph_list[1];
	assert_eq!(first_glyph.face_index, 0);
	assert!(second_glyph.position_x > first_glyph.position_x);
	assert!(!second_glyph.is_right_to_left);
}
필드fieldpub face_index: usize#0.4.0 부터since 0.4.0소스source

얼굴 목록 안의 자리. (SYSTEM_FACE_INDEX 면 브라우저 시스템 글꼴 조각)

Position in the face list. (a browser system font segment if SYSTEM_FACE_INDEX)

반환Returnsusize

필드fieldpub glyph_index: u16#0.4.0 부터since 0.4.0소스source

글리프 번호. (시스템 글꼴 조각이면 0)

Glyph index. (0 for a system font segment)

반환Returnsu16

필드fieldpub position_x: f32#0.4.0 부터since 0.4.0소스source

글리프 원점 x. (글 왼쪽 끝에서, 모양 짓기의 x 오프셋 포함)

Glyph origin x. (from the left end of the text, including the shaping x offset)

반환Returnsf32

필드fieldpub position_y: f32#0.4.0 부터since 0.4.0소스source

글리프 원점 y. (기준선에서, 모양 짓기의 y 오프셋)

Glyph origin y. (from the baseline, the shaping y offset)

반환Returnsf32

필드fieldpub text_start: usize#0.4.0 부터since 0.4.0소스source

시스템 글꼴 조각이면 그 조각의 글 자리. (바이트, face_index 가 SYSTEM_FACE_INDEX 일 때만)

For a system font segment, the text position of that segment. (bytes, only when face_index is SYSTEM_FACE_INDEX)

반환Returnsusize

필드fieldpub text_end: usize#0.4.0 부터since 0.4.0소스source

시스템 글꼴 조각의 글 끝 자리. (바이트, 끝은 빼고. 조각이 아니면 0)

Text end position of a system font segment. (bytes, end exclusive. 0 if not a segment)

반환Returnsusize

필드fieldpub is_right_to_left: bool#0.4.0 부터since 0.4.0소스source

든 줄기(run)가 오른쪽에서 왼쪽인지.

Whether the run it belongs to is right to left.

반환Returnsbool

필드fieldpub cluster_start: usize#0.4.0 부터since 0.4.0소스source

글리프가 든 글자 묶음(HarfBuzz cluster)의 글 시작 자리. (바이트, 시스템 글꼴 조각이면 조각 시작, 글리프 아틀라스가 글자 덩어리를 가른다)

Text start position of the grapheme cluster (HarfBuzz cluster) that holds the glyph. (bytes, the segment start for a system font segment; the glyph atlas uses it to split text chunks)

반환Returnsusize

ShapedTextstruct

소스source

모양 지은 글. (글리프는 왼쪽에서 오른쪽 그리는 차례)

Shaped text. (glyphs in left to right drawing order)

예제Example글 전체 전진폭Advance of the whole text
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face_list = vec![ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	}];
	let shaped_text = shape_text(&face_list, "abc", 20.0, ShapingDirection::LeftToRight, None);
	assert_eq!(shaped_text.glyph_list.len(), 3);
	let last_glyph = shaped_text.glyph_list[2];
	assert!(shaped_text.advance_width > last_glyph.position_x);
}
필드fieldpub glyph_list: Vec<ShapedGlyph>#0.4.0 부터since 0.4.0소스source

글리프 목록. (왼쪽부터 그리는 차례)

Glyph list. (drawing order from the left)

반환ReturnsVec<ShapedGlyph>

필드fieldpub advance_width: f32#0.4.0 부터since 0.4.0소스source

글 전체 전진폭. (픽셀)

Advance of the whole text. (pixels)

반환Returnsf32

GlyphRasterstruct

소스source

글리프 래스터 하나. (덮인 정도, 왼쪽 위 자리는 펜 원점에서 오른쪽 xmin, 기준선에서 위로 top)

  • coverage 는 색이 아닌 글자의 덮인 정도다. 색 글리프 몫은 color_pixels 에 제 색으로 든다. (프리멀티플라이드 RGBA, 같은 크기, 없으면 None)

One glyph raster. (coverage, the top left position is xmin to the right of the pen origin and top up from the baseline)

  • coverage is the coverage of non-color text. The color glyph part is held in its own colors in color_pixels. (premultiplied RGBA, same size, None if absent)
예제Example글리프 하나 래스터Rasterize one glyph
use std::rc::Rc;
use vanilla::core::textshaping::{rasterize_glyph, shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face = ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let shaped_text = shape_text(&[face.clone()], "A", 32.0, ShapingDirection::LeftToRight, None);
	let glyph_raster = rasterize_glyph(&face, shaped_text.glyph_list[0].glyph_index, 32.0);
	assert!(glyph_raster.width > 0 && glyph_raster.height > 0);
	assert_eq!(glyph_raster.coverage.len(), (glyph_raster.width * glyph_raster.height) as usize);
	assert!(glyph_raster.top_y > 0);
	assert!(glyph_raster.color_pixels.is_none());
}
필드fieldpub coverage: Vec<u8>#0.4.0 부터since 0.4.0소스source

덮인 정도. (0 ~ 255, width * height 개, 위 줄부터)

Coverage. (0 ~ 255, width * height values, from the top row)

반환ReturnsVec<u8>

필드fieldpub width: i32#0.4.0 부터since 0.4.0소스source

너비. (픽셀)

Width. (pixels)

반환Returnsi32

필드fieldpub height: i32#0.4.0 부터since 0.4.0소스source

높이. (픽셀)

Height. (pixels)

반환Returnsi32

필드fieldpub left_x: i32#0.4.0 부터since 0.4.0소스source

펜 원점에서 래스터 왼쪽까지. (픽셀, 오른쪽이 양수)

From the pen origin to the left of the raster. (pixels, right is positive)

반환Returnsi32

필드fieldpub top_y: i32#0.4.0 부터since 0.4.0소스source

기준선에서 래스터 위까지. (픽셀, 위가 양수)

From the baseline to the top of the raster. (pixels, up is positive)

반환Returnsi32

필드fieldpub color_pixels: Option<Vec<u8>>#0.4.0 부터since 0.4.0소스source

색 글리프 층. (프리멀티플라이드 RGBA, width * height * 4 바이트, 색 글리프가 아니면 None)

Color glyph layer. (premultiplied RGBA, width * height * 4 bytes, None if not a color glyph)

반환ReturnsOption<Vec<u8>>

함수Functions

함수functionpub fn parse_css_weight(weight_text: &str) -> Option<u16>#0.4.0 부터since 0.4.0소스source

CSS 굵기 값 하나 읽기. ("normal" 400, "bold" 700, 숫자 1 ~ 1000)

Reads one CSS weight value. ("normal" 400, "bold" 700, numbers 1 ~ 1000)

weight_text&str
CSS 굵기 값 하나. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)One CSS weight value. (leading and trailing spaces are trimmed, case-insensitive)

반환ReturnsOption<u16> 굵기. (소수는 반올림) 1 ~ 1000 밖이거나 읽지 못하면 None.Weight. (decimals are rounded) None if outside 1 ~ 1000 or unreadable.

예제Example낱말, 숫자, 범위 밖Words, numbers, out of range
use vanilla::core::textshaping::parse_css_weight;

assert_eq!(parse_css_weight("normal"), Some(400));
assert_eq!(parse_css_weight(" BOLD "), Some(700));
assert_eq!(parse_css_weight("450.6"), Some(451));
assert_eq!(parse_css_weight("1001"), None);
assert_eq!(parse_css_weight("heavy"), None);
함수functionpub fn parse_unicode_range(unicode_range: &str) -> Vec<(u32, u32)>#0.4.0 부터since 0.4.0소스source

unicode-range 글 → 코드 포인트 범위 목록. ("U+0-FF, U+4??" → [(0, 255), (1024, 1279)], 비었으면 빈 목록 = 모든 글자)

  • 원본 textstringtexturecache.js, uifont.js 의 parseUnicodeRange 와 같다.

unicode-range text → list of code point ranges. ("U+0-FF, U+4??" → [(0, 255), (1024, 1279)], an empty list if empty = all characters)

  • Same as parseUnicodeRange in the original textstringtexturecache.js and uifont.js.
unicode_range&str
쉼표로 이은 범위 글. (U+ 나 u+ 로 시작하지 않거나 16 진수가 아닌 조각은 넘긴다)Comma separated range text. (pieces that do not start with U+ or u+ or are not hexadecimal are skipped)

반환ReturnsVec<(u32, u32)> (처음, 끝) 코드 포인트 목록. (끝 포함)List of (start, end) code points. (end inclusive)

예제Example범위, 한 글자, ? 자리Range, single character, ? wildcard
use vanilla::core::textshaping::parse_unicode_range;

assert_eq!(parse_unicode_range("U+0-FF, U+4??"), vec![(0, 255), (0x400, 0x4FF)]);
assert_eq!(parse_unicode_range("U+0131"), vec![(0x131, 0x131)]);
assert!(parse_unicode_range("").is_empty());
함수functionpub fn is_emoji_presentation(grapheme: &str) -> bool#0.4.0 부터since 0.4.0소스source

글자 묶음이 이모지 표시인지. (UTS #51, 아니면 글 표시)

  • VS15(FE0E) 가 있으면 글 표시, VS16(FE0F) 이나 키캡(20E3)이 있으면 이모지 표시다.
  • 첫 글자가 Emoji_Presentation 이거나(국기의 지역 표시 글자 포함), 피부색 조정자나 태그 글자가 붙었거나, 이음 문자로 이은 이모지 묶음이면 이모지 표시다. ❤ 처럼 Emoji 이지만 Emoji_Presentation 이 아닌 글자 하나는 글 표시다. (크롬도 맨 ❤ 는 글 글꼴로 그린다)

Whether a grapheme cluster has emoji presentation. (UTS #51, otherwise text presentation)

  • Text presentation if it has VS15 (FE0E), emoji presentation if it has VS16 (FE0F) or a keycap (20E3).
  • Emoji presentation if the first character is Emoji_Presentation (including the regional indicators of flags), a skin tone modifier or tag characters are attached, or it is an emoji sequence joined with a joiner. A single character like ❤ that is Emoji but not Emoji_Presentation is text presentation. (Chrome also draws a plain ❤ with the text font)
grapheme&str
글자 묶음 하나.One grapheme cluster.

반환Returnsbool 이모지 표시면 true. (빈 글은 false)true for emoji presentation. (false for empty text)

함수functionpub fn calculate_weight_score(face_minimum_weight: u16, face_maximum_weight: u16, desired_weight: u16) -> (u32, u32)#0.4.0 부터since 0.4.0소스source

굵기 고르기 점수. (작을수록 먼저, CSS Fonts 4 의 차례. 굵기 범위가 청한 굵기를 품으면 (0, 0))

  • 청한 값이 400 ~ 500 이면 그 값부터 500 까지 오름, 그 아래 내림, 500 위 오름. 400 아래면 아래 내림, 위 오름. 500 위면 위 오름, 아래 내림.

Weight selection score. (smaller comes first, the CSS Fonts 4 order. (0, 0) if the weight range contains the requested weight)

  • If the requested value is 400 ~ 500, ascending from that value up to 500, then descending below it, then ascending above 500. Below 400, descending below then ascending above. Above 500, ascending above then descending below.
face_minimum_weightu16
얼굴 굵기 범위의 처음.Start of the face's weight range.
face_maximum_weightu16
얼굴 굵기 범위의 끝.End of the face's weight range.
desired_weightu16
청한 굵기.Requested weight.

반환Returns(u32, u32) (갈래, 굵기 차이). (튜플로 견주어 작은 것이 먼저)(group, weight difference). (compared as a tuple, smaller comes first)

예제Example400 을 청하면 500, 300, 600 차례Requesting 400 gives the order 500, 300, 600
use vanilla::core::textshaping::calculate_weight_score;

assert_eq!(calculate_weight_score(100, 900, 700), (0, 0));
assert!(calculate_weight_score(500, 500, 400) < calculate_weight_score(300, 300, 400));
assert!(calculate_weight_score(300, 300, 400) < calculate_weight_score(600, 600, 400));
함수functionpub fn find_collection_face_index(font_bytes: &[u8], desired_weight: u16, is_italic_desired: bool) -> u32#0.4.0 부터since 0.4.0소스source

글꼴 모음(TTC)에서 청한 굵기와 기울기에 가장 맞는 얼굴 번호. (모음이 아니면 0)

  • 굵기는 OS/2 의 usWeightClass, 기울기는 OS/2 와 head 의 기울임 표시로 본다. 기울기를 먼저, 그다음 굵기를 select_font_faces 와 같은 차례로 고른다.
  • PostScript 이름이 점으로 시작하는 얼굴(맥 시스템 글꼴이 안에서만 쓰는 얼굴)은 다른 얼굴이 없을 때만 고른다. 점수가 같으면 앞 번호.

Face index in a font collection (TTC) that best matches the requested weight and style. (0 if not a collection)

  • Weight comes from usWeightClass in OS/2, and style from the italic flags in OS/2 and head. Style is chosen first, then weight in the same order as select_font_faces.
  • Faces whose PostScript name starts with a dot (faces the Mac system font uses only internally) are chosen only when there is no other face. On a tie, the lower index.
font_bytes&[u8]
글꼴 바이트. (모음이나 글꼴 하나)Font bytes. (a collection or a single font)
desired_weightu16
청한 굵기.Requested weight.
is_italic_desiredbool
기울임을 청하는지.Whether italic is requested.

반환Returnsu32 얼굴 번호. (읽을 수 있는 얼굴이 없으면 0)Face index. (0 if there is no readable face)

함수functionpub fn read_weight_variation(font_bytes: &[u8], face_index: u32, desired_weight: u16) -> Vec<rustybuzz::Variation>#0.4.0 부터since 0.4.0소스source

가변 글꼴의 굵기 축 값. (wght 축이 있고 청한 굵기가 기본값과 다르면 축 범위로 자른 값 하나, 아니면 빈 목록)

Weight axis values of a variable font. (one value clamped to the axis range if there is a wght axis and the requested weight differs from the default, otherwise an empty list)

font_bytes&[u8]
글꼴 바이트.Font bytes.
face_indexu32
모음 안의 얼굴 번호. (모음이 아니면 0)Face index inside the collection. (0 if not a collection)
desired_weightu16
청한 굵기.Requested weight.

반환ReturnsVec<rustybuzz::Variation> wght 축 값 하나의 목록. 축이 없거나, 자른 값이 기본값과 0.5 안으로 같거나, 글꼴을 읽지 못하면 빈 목록.A list of one wght axis value. An empty list if there is no axis, the clamped value is within 0.5 of the default, or the font cannot be read.

함수functionpub fn read_weight_axis_range(font_bytes: &[u8], face_index: u32) -> Option<(u16, u16)>#0.4.0 부터since 0.4.0소스source

가변 글꼴의 굵기 범위. (wght 축의 처음과 끝, 축이 없으면 None)

Weight range of a variable font. (start and end of the wght axis, None if there is no axis)

font_bytes&[u8]
글꼴 바이트.Font bytes.
face_indexu32
모음 안의 얼굴 번호. (모음이 아니면 0)Face index inside the collection. (0 if not a collection)

반환ReturnsOption<(u16, u16)> (처음, 끝) 굵기. (반올림) 축이 없거나 글꼴을 읽지 못하면 None.(start, end) weight. (rounded) None if there is no axis or the font cannot be read.

함수functionpub fn select_font_faces(face_list: &[&RegisteredFontFace], desired_weight: u16, is_italic_desired: bool, output_list: &mut Vec<ResolvedFontFace>)#0.4.0 부터since 0.4.0소스source

한 이름 아래의 얼굴들에서 청한 굵기와 기울기에 맞는 얼굴들 고르기. (CSS Fonts 4 의 글꼴 고르기 차례)

  • 기울기를 먼저 고른다. 기울임을 청하면 기울인 얼굴, 없으면 바른 얼굴(가짜 기울임). 바르게를 청하면 바른 얼굴, 없으면 기울인 얼굴.
  • 굵기: 청한 값이 400 ~ 500 이면 그 값부터 500 까지 오름, 그 아래 내림, 500 위 오름. 400 아래면 아래 내림, 위 오름. 500 위면 위 오름, 아래 내림.
  • 고른 굵기와 기울기의 얼굴을 모두 나중 것부터 돌려준다. (글자 범위로 나눠 그린다)

Chooses the faces matching the requested weight and style from the faces under one name. (the CSS Fonts 4 font matching order)

  • Style is chosen first. If italic is requested, an italic face, or an upright face if none (fake italic). If upright is requested, an upright face, or an italic face if none.
  • Weight: if the requested value is 400 ~ 500, ascending from that value up to 500, then descending below it, then ascending above 500. Below 400, descending below then ascending above. Above 500, ascending above then descending below.
  • Returns all faces with the chosen weight and style, latest first. (drawing is split by character range)
face_list&[&RegisteredFontFace]
한 이름 아래의 얼굴들. (비었으면 아무것도 더하지 않는다)Faces under one name. (adds nothing if empty)
desired_weightu16
청한 굵기.Requested weight.
is_italic_desiredbool
기울임을 청하는지.Whether italic is requested.
output_list&mut Vec<ResolvedFontFace>
고른 얼굴을 뒤에 더할 목록. (있던 것은 그대로 둔다)List to append the chosen faces to. (existing items are kept)
예제Example바른 보통 얼굴 하나에 굵은 기울임을 청하면 가짜로 입힌다Requesting bold italic with only one upright regular face applies them as fakes
use std::rc::Rc;
use vanilla::core::textshaping::{select_font_faces, LoadedFont, RegisteredFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::FontFaceDescriptors;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let regular_face = RegisteredFontFace {
		descriptors: FontFaceDescriptors::new(),
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		order_number: 1,
	};
	let mut resolved_face_list = Vec::new();
	select_font_faces(&[&regular_face], 700, true, &mut resolved_face_list);
	assert!(resolved_face_list[0].is_synthetic_bold);
	assert!(resolved_face_list[0].is_synthetic_italic);
}
함수functionpub fn find_chrome_word_end(text: &str, start: usize, is_latin1: bool) -> usize#0.4.0 부터since 0.4.0소스source

크롬 캔버스의 낱말 끝. (platform/fonts/plain_text_node.cc 의 NextWordEndIndex. text 의 바이트 자리 start 에서 시작하는 낱말의 끝 바이트 자리)

  • 빈칸(U+0020), 탭, ZWSP 는 하나씩 따로 낱말이다. is_latin1 (크롬의 8 비트 글, 모든 글자가 U+00FF 이하)이면 빈칸과 탭에서만 끊는다.
  • 그 밖: 한중일 글자나 기호가 아닌 글자로 시작하면 빈칸이나 한중일 글자(결합 부호 따위가 아닌 것) 앞에서 끊는다. 한중일이나 이모지로 시작하면 글자마다 끊되 결합 부호, 수식 글자, ZWJ, 이모지 성분, 그림 문자는 붙이고, 문자가 Common, Inherited 인 한중일 기호와 첫 글자가 Common 일 때 다음 한 글자도 붙인다.

Word end of Chrome's canvas. (NextWordEndIndex in platform/fonts/plain_text_node.cc. The end byte position of the word starting at byte position start of text)

  • Spaces (U+0020), tabs and ZWSP are separate words, one each. If is_latin1 (Chrome's 8 bit text, every character U+00FF or below), it breaks only at spaces and tabs.
  • Otherwise: if it starts with a character that is not a CJK character or symbol, it breaks before a space or a CJK character (one that is not a combining mark or the like). If it starts with CJK or emoji, it breaks at every character but attaches combining marks, modifier letters, ZWJ, emoji components and pictographs, CJK symbols whose script is Common or Inherited, and, when the first character is Common, the next character too.
text&str
글.Text.
startusize
낱말이 시작하는 바이트 자리. (글자 경계여야 한다, 아니면 패닉)Byte position where the word starts. (must be a character boundary, otherwise it panics)
is_latin1bool
글의 모든 글자가 U+00FF 이하인지.Whether every character in the text is U+00FF or below.

반환Returnsusize 낱말 끝 바이트 자리. (끝은 빼고) start 가 글 끝이면 start.Word end byte position. (end exclusive) start if start is at the end of the text.

예제Example빈칸은 따로, 한자는 글자마다Spaces are separate, Han characters are per character
use vanilla::core::textshaping::find_chrome_word_end;

let text = "ab cd";
assert_eq!(find_chrome_word_end(text, 0, true), 2);
assert_eq!(find_chrome_word_end(text, 2, true), 3);
assert_eq!(find_chrome_word_end(text, 3, true), 5);
let ideograph_text = "\u{4E00}\u{4E8C}";
assert_eq!(find_chrome_word_end(ideograph_text, 0, false), 3);
assert_eq!(find_chrome_word_end(ideograph_text, 3, false), 6);
함수functionpub fn shape_text(face_list: &[ResolvedFontFace], text: &str, pixel_size: f32, direction: ShapingDirection, system_font_measure: Option<SystemFontMeasure>) -> ShapedText#0.4.0 부터since 0.4.0소스source

글 모양 짓기. (양방향 정렬 → 얼굴마다 나눈 조각을 rustybuzz 로 모양 짓기 → 왼쪽부터 놓기)

  • direction 은 문단의 방향이다. (원본 canvas.direction) 문단 안의 글자 순서는 양방향 알고리즘이 정한다.
  • 줄바꿈 문자는 한 줄로 보고 그대로 모양 짓는다. (원본 fillText 도 줄을 바꾸지 않는다)
  • system_font_measure 를 주면(웹) 올린 어느 얼굴에도 없는 글자 묶음은 브라우저 시스템 글꼴 조각(SYSTEM_FACE_INDEX)으로 둔다. 원본 브라우저의 글꼴 대체와 같다. 이모지 표시 묶음인데 올린 얼굴에 색 글리프가 없으면 흑백 글리프가 있어도 브라우저 조각(색 이모지)으로 둔다. (크롬도 ❤️ 는 색 이모지 글꼴로 그린다) 주지 않으면 첫 얼굴의 빈 글리프로 그린다.

Shapes text. (bidirectional ordering → shapes the per-face segments with rustybuzz → places them from the left)

  • direction is the paragraph direction. (the original canvas.direction) The character order inside the paragraph is decided by the bidirectional algorithm.
  • Line break characters are treated as one line and shaped as they are. (the original fillText does not break lines either)
  • If system_font_measure is given (web), grapheme clusters not in any loaded face become browser system font segments (SYSTEM_FACE_INDEX). Same as the browser font fallback in the original. If a cluster has emoji presentation and the loaded faces have no color glyph, it becomes a browser segment (color emoji) even if a monochrome glyph exists. (Chrome also draws ❤️ with a color emoji font) If not given, it is drawn with the first face's empty glyph.
face_list&[ResolvedFontFace]
고른 얼굴들. (글자 묶음마다 앞 얼굴부터 찾는다)Chosen faces. (searched from the first face for each grapheme cluster)
text&str
모양 지을 글.Text to shape.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
directionShapingDirection
문단 방향.Paragraph direction.
system_font_measureOption<SystemFontMeasure>
시스템 글꼴 조각 재기. (웹, None 이면 조각을 두지 않는다)Measures a system font segment. (web, no segments are made if None)

반환ReturnsShapedText 모양 지은 글. 얼굴이 없거나 글이 비었으면 글리프 없이 전진폭 0.The shaped text. No glyphs and advance 0 if there are no faces or the text is empty.

예제Example크기가 커지면 전진폭도 커진다A larger size gives a larger advance
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face_list = vec![ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	}];
	let small_text = shape_text(&face_list, "Hello", 16.0, ShapingDirection::LeftToRight, None);
	let large_text = shape_text(&face_list, "Hello", 32.0, ShapingDirection::LeftToRight, None);
	assert!(large_text.advance_width > small_text.advance_width);
	let empty_text = shape_text(&face_list, "", 16.0, ShapingDirection::LeftToRight, None);
	assert!(empty_text.glyph_list.is_empty());
	assert_eq!(empty_text.advance_width, 0.0);
}
함수functionpub fn calculate_synthetic_bold_radius(pixel_size: f32) -> f32#0.4.0 부터since 0.4.0소스source

가짜 굵게의 넓히는 반지름. (픽셀, Skia 의 칠하는 두께의 반)

Widening radius of fake bold. (pixels, half of Skia's stroke thickness)

pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsf32 반지름. (픽셀, 9px 이하는 크기의 1/48, 36px 이상은 1/64, 사이는 곧게 잇는다)Radius. (pixels, 1/48 of the size at 9px or less, 1/64 at 36px or more, linearly interpolated in between)

예제Example36px 이상은 크기의 1/641/64 of the size at 36px or more
use vanilla::core::textshaping::calculate_synthetic_bold_radius;

assert_eq!(calculate_synthetic_bold_radius(48.0), 0.75);
assert!((calculate_synthetic_bold_radius(6.0) - 0.125).abs() < 0.00001);
함수functionpub fn rasterize_glyph(face: &ResolvedFontFace, glyph_index: u16, pixel_size: f32) -> GlyphRaster#0.4.0 부터since 0.4.0소스source

글리프 래스터. (가짜 굵게는 넓히고, 가짜 기울임은 기준선 기준으로 민다. 색 글리프는 제 색으로, 가짜 굵게 없이)

Rasterizes a glyph. (fake bold widens, fake italic shears around the baseline. Color glyphs in their own colors, without fake bold)

face&ResolvedFontFace
그릴 얼굴. (가짜 굵게, 가짜 기울임을 입힐지 함께)Face to draw with. (together with whether to apply fake bold and fake italic)
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환ReturnsGlyphRaster 래스터. 윤곽이 없는 글리프(빈칸)는 너비와 높이가 0.The raster. A glyph without an outline (space) has width and height 0.

예제Example가짜 굵게는 래스터를 넓힌다Fake bold widens the raster
use std::rc::Rc;
use vanilla::core::textshaping::{rasterize_glyph, shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face = ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let bold_face = ResolvedFontFace {
		is_synthetic_bold: true,
		..face.clone()
	};
	let glyph_index = shape_text(&[face.clone()], "H", 32.0, ShapingDirection::LeftToRight, None).glyph_list[0].glyph_index;
	let glyph_raster = rasterize_glyph(&face, glyph_index, 32.0);
	let bold_glyph_raster = rasterize_glyph(&bold_face, glyph_index, 32.0);
	assert!(bold_glyph_raster.width > glyph_raster.width);
	assert!(bold_glyph_raster.left_x < glyph_raster.left_x);
}
함수functionpub fn is_subpixel_positioned(face: &ResolvedFontFace, pixel_size: f32) -> bool#0.4.0 부터since 0.4.0소스source

글리프 자리를 1/4 픽셀 서브픽셀로 나눌지. (크롬 블링크가 SkFont::setSubpixel 에 주는 값)

  • 맥, 윈도우: 늘 켠다. (안티에일리어스 글)
  • 리눅스: fontconfig 의 힌팅이 꽉(hintfull)이면 끄고 그 밖은 켠다. (WebFontRenderStyle::ApplyToSkFont 의 force_subpixel_positioning 은 힌팅이 kFull 이 아닐 때 참이고, use_subpixel_positioning 은 기기 배율이 1 보다 클 때만 참이다. 안티에일리어스가 꺼진 글꼴은 크롬 GetFontRenderParams 가 힌팅을 꽉으로 바꾼다) 얼굴의 가족 이름, 크기, 굵기, 기울기로 묻는다. (rasterize_glyph_at 의 힌팅과 같은 물음)
  • 그 밖(웹): 끈다. (브라우저 캔버스가 정한다)

Whether to split glyph positions into 1/4 pixel subpixels. (the value Chrome Blink gives SkFont::setSubpixel)

  • Mac, Windows: always on. (antialiased text)
  • Linux: off when fontconfig hinting is full (hintfull), otherwise on. (In WebFontRenderStyle::ApplyToSkFont, force_subpixel_positioning is true when hinting is not kFull, and use_subpixel_positioning is true only when the device scale is greater than 1. For fonts with antialiasing off, Chrome GetFontRenderParams changes hinting to full) Queried by the face's family name, size, weight, and slant. (the same query as the hinting in rasterize_glyph_at)
  • Otherwise (web): off. (the browser canvas decides)
face&ResolvedFontFace
그릴 얼굴.Face to draw.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsbool 켜면 true. 끄면 글리프 자리를 반올림한 정수 자리에 두고 서브픽셀 몫은 0 이다.true when on. When off, the glyph is placed at the rounded integer position and the subpixel part is 0.

예제Example맥과 윈도우는 늘 켠다Mac and Windows are always on
use std::rc::Rc;
use vanilla::core::textshaping::{is_subpixel_positioned, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::FontFaceDescriptors;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face = ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let is_subpixel = is_subpixel_positioned(&face, 16.0);
	if cfg!(any(target_os = "macos", target_os = "windows")) {
		assert!(is_subpixel);
	}
}
함수functionpub fn rasterize_glyph_at(face: &ResolvedFontFace, glyph_index: u16, pixel_size: f32, subpixel_x: f32, luminance_color: [u8; 3]) -> GlyphRaster#0.4.0 부터since 0.4.0소스source

서브픽셀 자리와 글자 색 밝기로 글리프 래스터. (맥은 CoreText, 윈도우는 DirectWrite, 리눅스는 skrifa 힌팅 윤곽으로 크롬처럼 그린다)

  • 맥: 색이 아닌 글리프는 크롬 맥 Canvas2D 와 같은 길로 그린다. (스키아 SkScalerContext_Mac 의 A8 마스크: 글꼴 부드럽게, CoreGraphics 감마 풀기, 글자 색 밝기의 감마 전보정) 글자 색 밝기는 맥 스키아처럼 글꼴 부드럽게가 회색이면 1/2 을 곱한 색의 3 비트 단계이고, 감마는 크롬 맥의 sRGB, 대비는 0 이다. (SkTypeface_Mac::onFilterRec, 크로미엄 skia/BUILD.gn) 가짜 기울임은 CoreText 의 글자 행렬 기울기로 그린다. 색 글리프는 rasterize_glyph 와 같다.
  • 윈도우: 색이 아닌 글리프는 크롬 윈도우 Canvas2D 와 같은 길로 DirectWrite 가 그린다. (스키아 SkScalerContext_DW 의 A8: 격자 맞춤, gasp 로 고른 렌더링 모드, ClearType 이 켜졌으면 크롬처럼 3x1 텍스처의 세 채널 평균, 꺼졌으면 그레이스케일) 감마 전보정은 글자 색 밝기 단계의 표로, 대비와 감마는 크롬처럼 Avalon.Graphics 키가 있으면 시스템 값, 없으면 대비 1, sRGB 다. 가짜 기울임은 DirectWrite 글자 행렬의 기울기다.
  • 리눅스: 색이 아닌 글리프는 크롬 리눅스처럼 skrifa 윤곽에 fontconfig 의 힌팅 단계로 힌팅을 걸어 스키아와 같은 해석적 AA 로 칠하고 감마 1.2, 대비 0.2 로 전보정한다. (스키아 SkTypeface_Fontations, SkScan_AAAPath) fontconfig 힌팅이 꽉(hintfull)인 글꼴은 서브픽셀 자리를 끈다. (is_subpixel_positioned, 부르는 쪽이 subpixel_x 를 0 으로 준다)
  • 그 밖은 서브픽셀 자리와 밝기를 쓰지 않는다.

Glyph raster by subpixel position and text color luminance. (Mac uses CoreText, Windows uses DirectWrite, Linux draws like Chrome with hinted skrifa outlines)

  • Mac: non-color glyphs are drawn the same way as Chrome Mac Canvas2D. (the A8 mask of Skia SkScalerContext_Mac: font smoothing, undoing CoreGraphics gamma, gamma precorrection by text color luminance) As in Mac Skia, the text color luminance is a 3-bit step of the color multiplied by 1/2 when font smoothing is gray, the gamma is Chrome Mac's sRGB, and the contrast is 0. (SkTypeface_Mac::onFilterRec, Chromium skia/BUILD.gn) Fake italic is drawn with the slant of the CoreText text matrix. Color glyphs are the same as rasterize_glyph.
  • Windows: non-color glyphs are drawn by DirectWrite the same way as Chrome Windows Canvas2D. (the A8 of Skia SkScalerContext_DW: grid fitting, the rendering mode picked by gasp, when ClearType is on the average of the three channels of a 3x1 texture like Chrome, otherwise grayscale) Gamma precorrection uses a table by text color luminance step, and contrast and gamma are the system values if the Avalon.Graphics key exists, otherwise contrast 1 and sRGB, like Chrome. Fake italic is the slant of the DirectWrite text matrix.
  • Linux: non-color glyphs are painted like Chrome Linux by hinting skrifa outlines with fontconfig's hinting level, filled with the same analytic AA as Skia, and precorrected with gamma 1.2 and contrast 0.2. (Skia SkTypeface_Fontations, SkScan_AAAPath) Fonts whose fontconfig hinting is full (hintfull) turn off subpixel positioning. (is_subpixel_positioned; the caller passes 0 for subpixel_x)
  • Otherwise subpixel position and luminance are not used.
face&ResolvedFontFace
그릴 얼굴. (가짜 굵게, 가짜 기울임을 입힐지 함께)Face to draw with. (together with whether to apply fake bold and fake italic)
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
subpixel_xf32
서브픽셀 가로 자리. (0, 0.25, 0.5, 0.75, 스키아처럼 글리프 자리에 1/8 을 더해 내린 정수 자리의 나머지를 1/4 단위로 내린 값)Horizontal subpixel position. (0, 0.25, 0.5, 0.75; like Skia, the remainder of the integer position obtained by adding 1/8 to the glyph position and flooring, floored to 1/4 steps)
luminance_color[u8; 3]
글자 색. (sRGB 의 빨강, 초록, 파랑, 원본처럼 흰색으로 굽는 글은 [255, 255, 255])Text color. (red, green, blue in sRGB; [255, 255, 255] for text baked white like the original)

반환ReturnsGlyphRaster 래스터. 윤곽이 없는 글리프(빈칸)는 너비와 높이가 0. left_x 는 서브픽셀 몫을 뺀 정수 자리에서 잰다.The raster. A glyph without an outline (a space) has width and height 0. left_x is measured from the integer position without the subpixel part.

예제Example서브픽셀 자리를 옮겨도 덮인 정도의 합은 거의 같다Moving the subpixel position keeps the coverage sum almost the same
use std::rc::Rc;
use vanilla::core::textshaping::{rasterize_glyph_at, shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("H", 400, false, false) {
	let face = ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let glyph_index = shape_text(&[face.clone()], "H", 24.0, ShapingDirection::LeftToRight, None).glyph_list[0].glyph_index;
	let glyph_raster = rasterize_glyph_at(&face, glyph_index, 24.0, 0.0, [255, 255, 255]);
	let shifted_glyph_raster = rasterize_glyph_at(&face, glyph_index, 24.0, 0.5, [255, 255, 255]);
	let sum = |coverage: &[u8]| coverage.iter().map(|value| *value as u32).sum::<u32>() as f32;
	assert!(glyph_raster.width > 0 && shifted_glyph_raster.width > 0);
	assert!((sum(&glyph_raster.coverage) / sum(&shifted_glyph_raster.coverage) - 1.0).abs() < 0.1);
}
함수functionpub fn dilate_coverage(coverage: &[u8], width: i32, height: i32, radius: f32) -> Vec<u8>#0.4.0 부터since 0.4.0소스source

덮인 정도를 원 모양으로 넓히기. (가짜 굵게, 윤곽을 바깥으로 radius 픽셀 민 것)

  • 덮인 정도를 픽셀 가운데에서 윤곽까지의 거리로 본다. (덮인 정도 - 0.5, 안이 양수) 이웃 픽셀의 거리에서 이웃까지의 거리를 뺀 가장 큰 값에 radius 를 더해 다시 덮인 정도로 바꾼다. 곧은 윤곽은 정확히 radius 만큼 밀린다.

Widens coverage in a circular shape. (fake bold, the outline pushed outward by radius pixels)

  • Treats coverage as the distance from the pixel center to the outline. (coverage - 0.5, inside is positive) Takes the largest of the neighbor pixels' distances minus the distance to that neighbor, adds radius and converts it back to coverage. A straight outline is pushed by exactly radius.
coverage&[u8]
덮인 정도. (0 ~ 255, width * height 개)Coverage. (0 ~ 255, width * height values)
widthi32
너비. (픽셀)Width. (pixels)
heighti32
높이. (픽셀)Height. (pixels)
radiusf32
넓힐 반지름. (픽셀, 0 이하면 그대로 복사)Radius to widen by. (pixels, copied as is if 0 or less)

반환ReturnsVec<u8> 넓힌 덮인 정도. (같은 크기, 원래 값보다 작아지지 않는다)Widened coverage. (same size, never smaller than the original values)

예제Example두 열짜리 막대를 반 픽셀 넓히기Widen a two-column bar by half a pixel
use vanilla::core::textshaping::dilate_coverage;

let width = 8;
let height = 3;
let mut coverage = vec![0u8; (width * height) as usize];
for position_y in 0..height {
	coverage[(position_y * width + 3) as usize] = 255;
	coverage[(position_y * width + 4) as usize] = 255;
}
let dilated_coverage = dilate_coverage(&coverage, width, height, 0.5);
assert_eq!(dilated_coverage[(width + 3) as usize], 255);
assert!((dilated_coverage[(width + 2) as usize] as i32 - 128).abs() <= 2);
assert_eq!(dilated_coverage[width as usize], 0);
함수functionpub fn shear_coverage(coverage: &[u8], bitmap_width: i32, bitmap_height: i32, baseline_y: f32, shear: f32) -> Vec<u8>#0.4.0 부터since 0.4.0소스source

덮인 정도를 가로로 기울이기. (기준선 위 줄은 오른쪽, 아래 줄은 왼쪽으로 줄 높이 × 기울기만큼 밀고, 두 픽셀 사이는 섞는다)

Shears coverage horizontally. (rows above the baseline move right and rows below move left by row height × slant, blending between two pixels)

coverage&[u8]
덮인 정도. (0 ~ 255, bitmap_width * bitmap_height 개)Coverage. (0 ~ 255, bitmap_width * bitmap_height values)
bitmap_widthi32
너비. (픽셀)Width. (pixels)
bitmap_heighti32
높이. (픽셀)Height. (pixels)
baseline_yf32
기준선 자리. (위에서 픽셀)Baseline position. (pixels from the top)
shearf32
기울기. (1 픽셀 올라갈 때 오른쪽으로 밀리는 픽셀)Slant. (pixels pushed right for every 1 pixel up)

반환ReturnsVec<u8> 기울인 덮인 정도. (같은 크기, 밖으로 밀린 몫은 잘린다)Sheared coverage. (same size, parts pushed outside are cut off)

예제Example기준선 위 세로 막대가 오른쪽으로 밀린다A vertical bar above the baseline moves right
use vanilla::core::textshaping::shear_coverage;

let width = 12;
let height = 12;
let mut coverage = vec![0u8; (width * height) as usize];
for position_y in 0..10 {
	coverage[(position_y * width + 5) as usize] = 255;
}
let sheared_coverage = shear_coverage(&coverage, width, height, 10.0, 0.5);
let top_row = &sheared_coverage[0..width as usize];
assert_eq!(top_row[5], 0);
assert!(top_row[9] > 0 && top_row[10] > 0);

상수Constants

상수constantpub const SYNTHETIC_ITALIC_SKEW: f32 = 0.25#0.4.0 부터since 0.4.0소스source

가짜 기울임의 기울기. (기준선에서 1 픽셀 올라갈 때 오른쪽으로 밀리는 픽셀, Chromium setSkewX(-1/4))

Slant of fake italic. (pixels pushed right for every 1 pixel up from the baseline, Chromium setSkewX(-1/4))

반환Returnsf32

상수constantpub const BOLD_WEIGHT_THRESHOLD: u16 = 600#0.4.0 부터since 0.4.0소스source

굵게로 보는 굵기의 문턱. (Blink kBoldThreshold)

Weight threshold that counts as bold. (Blink kBoldThreshold)

반환Returnsu16

상수constantpub const SYSTEM_FACE_INDEX: usize = usize::MAX#0.4.0 부터since 0.4.0소스source

브라우저 시스템 글꼴로 그리는 조각의 얼굴 자리. (웹에서 올린 어느 글꼴에도 없는 글자, ShapedGlyph.face_index)

Face position for segments drawn with the browser system font. (characters not in any font loaded on the web, ShapedGlyph.face_index)

반환Returnsusize

ShapingDirectionenum traits Clone, Copy, Debug, PartialEq, Eq, Hash

소스source

글 방향. (원본 Canvas2D direction 의 실제 값 "ltr" / "rtl")

Text direction. (the actual value "ltr" / "rtl" of the original Canvas2D direction)

이름Name설명Description
LeftToRight왼쪽에서 오른쪽. (원본 "ltr")Left to right. (the original "ltr")
RightToLeft오른쪽에서 왼쪽. (원본 "rtl")Right to left. (the original "rtl")