vanilladocs
vanillapunch.com
API / core/textstringtexturecache

core/textstringtexturecache

문자열 텍스처 캐시.

  • 원본은 글꼴(모드, 글꼴 글, 굽는 배율, 선 굵기)마다 글자 덩어리를 글리프 아틀라스(1024 x 1024 장, 8 장까지)에 한 번만 굽고, 글은 글리프 사각형 목록(엔트리, LRU 상한 1024)으로 그린다.
  • 데스크탑은 글자 모양 짓기(textshaping.rs: 양방향 정렬, rustybuzz 모양 짓기)로 글리프를 놓고, 처음 보는 글리프만 래스터화해(맥 CoreText, 윈도우 DirectWrite, 리눅스 skrifa) 아틀라스 칸에 굽는다. 칸은 원본과 같은 글자 덩어리마다 하나다. 한글, 한자, 가나, 숫자, 문장 부호, 이모지는 글자 묶음마다, 라틴과 키릴 같은 글자는 낱말째 한 칸이다. 칸 열쇠는 덩어리에 든 글리프마다 (얼굴, 글리프 번호, 크기, 스키아 서브픽셀 1/4 칸)과 첫 글리프에서의 정수 자리 차이, 방식과 선 굵기, 안티앨리어싱이다. (원본은 스키아의 칸 경계를 모두 담는 1/8 자리 칸을 열쇠로 쓴다. 러스트는 스키아가 쓰는 칸 자체를 알아 같은 래스터를 더 적게 굽는다) 이웃 덩어리의 잉크가 닿으면 칸마다 따로 그려 소수 자리의 선형 거르기와 겹친 잉크 섞기가 문자열째와 조금 다를 수 있다. (원본과 같다, 스키아 글리프 캐시와 TextMeshPro 의 꼴) 칸마다 위아래에 가장자리 줄을 한 줄씩 되풀이해 굽는다. (세로 소수 자리에서 칸 끝을 넘어 뽑아도 아틀라스의 다른 줄이 아니라 예전 CLAMP_TO_EDGE 처럼 가장자리 줄이 나온다) 256px 넘는 글꼴, 오른쪽에서 왼쪽 글, 웹(브라우저 Canvas2D 로 굽는다)은 원본처럼 문자열째 칸 하나에 굽는다. 장 정책(가장 나중에 연 장에만 이어 놓기, 차면 새 장, 8 장을 넘으면 가장 오래 안 쓴 장을 비우기), 엔트리 상한, 엔트리 키 구성(방식, 문단 방향, 폰트 문자열, 선 두께, 배율, 글)은 원본과 같다. 원본은 키를 문자열로 이어 붙인다. 여기서는 찾을 때마다 문자열을 만들지 않게 키의 해시로 찾고, 같은 해시 안에서 키를 하나씩 맞춰 본다.
  • 글자는 흰색으로 굽고, 그릴 때 색을 곱한다. (색이 바뀌어도 다시 굽지 않는다) 색 글리프(이모지)는 제 색으로 흰 글자 위에 얹어 굽는다. 원본도 흰색으로 fillText 한 캔버스를 올리므로 이모지는 제 색으로 구워지고 그릴 때 같은 색이 곱해진다. 외곽선(Stroke)으로 구울 때도 색 글리프는 테를 긋지 않고 색 그대로 얹는다. (크롬 strokeText 와 같다)
  • 폰트 문자열은 Canvas2D font 와 같은 꼴(CSS font 줄임 꼴)을 읽는다. 예: "16px DOSGothic", "bold 24px default", "italic 500 16px default", "12pt 'A B', C, sans-serif" 크기는 px 밖의 CSS 단위(ex, ch, cap, ic, lh, rem, 뷰포트 단위 포함), 이름 크기, calc() 도 크롬 캔버스처럼 읽고 "/줄높이"는 넘긴다. 쉼표로 이은 이름 목록은 글자마다 앞 이름의 얼굴부터 찾는다. (브라우저의 글꼴 목록과 같다, parse_font_string)
  • 글꼴은 원본 document.fonts 처럼 이름 하나 아래에 얼굴(굵기, 기울기, 글자 범위)을 여럿 올린다. (register_font_face) 고르기는 CSS 의 차례를 따르고, 기울인 얼굴이 없으면 가짜 기울임(기울기 1/4), 굵은 얼굴이 없으면 가짜 굵게를 글리프마다 입힌다. (textshaping.rs)
  • 이름의 얼굴들에 없는 글자는 기본 폰트, 시스템 글꼴 사슬, 표준 글꼴(데스크탑, 크롬의 -webkit-standard), 대체 폰트 순으로 찾는다. (브라우저의 글꼴 대체와 같은 자리) 이름 목록에서 얼굴을 하나도 찾지 못하면(default 가 아닌 없는 이름뿐이면) 크롬처럼 표준 글꼴을 기본 폰트보다 먼저 둔다. 데스크탑 시스템 글꼴 사슬(set_system_font_chain)은 원본 SYSTEM_FONT_STRING 의 이름을 운영체제 글꼴에서 찾은 것이고, 기본 글꼴 이름 default 를 청했을 때만 기본 폰트 뒤에 잇는다. 켜면 폰트 문자열의 올리지 않은 이름도 운영체제 글꼴에서 찾는다. 얼굴은 그 굵기와 기울기의 글자를 처음 쓸 때 읽는다. (platform/desktop/systemfont.rs) 대체 글꼴은 운영체제가 고른다. (set_system_font_fallback_enabled, 굵게를 청하면 굵은 얼굴을 따로 묻는다) 크롬처럼 첫 글꼴(빈칸을 가진 첫 얼굴)과 폰트 문자열마다 따로 묻고, 대체 얼굴은 운영체제가 그 얼굴을 고른 글자만 그린다. 이름 목록의 얼굴이 정준 분해로 그리는 글자(ï 를 i 와 U+0308 로)는 묻지 않는다. 후보 파일을 주면(add_fallback_font_candidate) 그것을 먼저 쓴다. 후보 파일은 쓸 때 읽는다. 이모지 표시 글자는 색 글리프 표가 있는 후보를, 그 밖의 글자는 색 글리프 표가 없는 후보를 먼저 읽는다. (표 목록만 먼저 엿본다)
  • 글꼴 얼굴을 새로 올리면 그 이름을 쓰는 폰트 문자열로 구웠고 그 얼굴의 글자 범위에 든 글자가 있는 문자열만 버린다. (원본 invalidateFontFaces) 원본처럼 set_rebake_text_on_font_load 로 켰을 때만 한다. (엔진이 EngineConfiguration.rebake_text_on_font_load 로 켠다, 기본 끔) 끄면 받기 전에 다른 글꼴로 구운 글자는 캐시에서 밀려날 때까지 그대로 남는다. 얼굴 지우기와 차례 바꾸기는 켜짐과 상관없이 버린다. 기본 폰트와 대체 폰트를 바꾸면 모두 버린다.
  • 웹은 원본처럼 늘 브라우저 Canvas2D 로 굽고 잰다. (platform/web/systemfont.rs) 올린 글꼴 바이트는 document.fonts 에 FontFace 로 올려 브라우저가 고르고 그린다. 올린 글꼴이 받아지면(loadingdone) 프레임 시작에 구운 글을 버린다. 데스크탑은 위의 모양 짓기와 래스터로 굽는다.
  • 글자 안티앨리어싱(set_text_antialias_enabled, 원본 setTextAntialiasEnabled): 끄면 구운 글자의 알파를 문턱값 128 로 0 과 255 로 가르고 텍스처를 NEAREST 로 뽑는다. 도트 글꼴을 설계 크기의 정수 배로 그리는 프로젝트가 끈다. 원본은 모듈 전역 값이고 이미 구운 글자는 그대로 둔다. 여기서는 캐시가 들고, 켜짐 여부를 키에 넣어 바꾼 다음 그리는 글자부터 바로 그 방식으로 굽는다. (rasterize_text 는 원본 ShadowText 처럼 받지 않는다)
  • 글 재기(measure_text)는 폰트 문자열과 글이 같으면 다시 재지 않는다. (원본 measureTextMetrics 의 캐시, 2048 개) 원본은 넘칠 때마다 가장 오래 안 쓴 하나를 버린다. 여기서는 넘치면 오래 안 쓴 반을 한 번에 버린다. (하나씩 찾으면 넘친 뒤로 잴 때마다 2048 개를 훑는다) 글꼴을 새로 등록하면 비운다. (원본은 웹 글꼴이 받아지면 비운다) measure_text 가 &self 라 캐시는 RefCell 에 든다.
  • 얼굴을 그때그때 받기(watch_unresolved_family_characters, take_unresolved_family_characters): 원본 브라우저는 올려 둔 FontFace 의 글자 범위에 든 글자를 그릴 때 그 얼굴을 받는다. 러스트 판은 지켜보는 이름으로 재거나 구운 글에서 올린 얼굴의 범위에 들지 않은 글자를 모으고, UIFont 가 update 에서 꺼내 그 글자의 조각을 받는다.
  • Graphic 없이 재기(measure_text_without_graphic): 원본은 어디서든 공용 2D 캔버스로 글을 잰다. 러스트 판은 글꼴을 등록할 때마다 글꼴 목록(Rc)을 스레드 하나의 전역에 알려 두고, 그 목록으로 잰다. UI 레이아웃이 그리기 전에 글 줄 수를 알아야 할 때 쓴다. (UIConfirmWindow)

String texture cache.

  • The original bakes text chunks once per font (mode, font string, bake scale, line width) into a glyph atlas (1024 x 1024 pages, up to 8 pages), and text is drawn as a list of glyph rectangles (entries, LRU limit 1024).
  • Desktop places glyphs with text shaping (textshaping.rs: bidirectional ordering, rustybuzz shaping), rasterizes only glyphs seen for the first time (CoreText on Mac, DirectWrite on Windows, skrifa on Linux) and bakes them into atlas cells. There is one cell per text chunk, the same chunks as the original. Hangul, Han, kana, digits, punctuation and emoji get one cell per grapheme cluster, and letters such as Latin and Cyrillic get one cell per word. The cell key is, for every glyph in the chunk, (face, glyph index, size, Skia 1/4 subpixel slot) and its integer offset from the first glyph, plus mode and line width and antialiasing. (The original keys by a 1/8 position slot that holds every Skia slot boundary. Rust knows the slot Skia itself uses, so it bakes fewer copies of the same raster) Where the ink of neighboring chunks touches, each cell is drawn separately, so linear filtering at fractional positions and blending of overlapping ink can differ slightly from the whole string. (Same as the original, the shape of the Skia glyph cache and TextMeshPro) One row above and below each cell is baked as a repeat of the edge row. (Sampling past the cell edge at a fractional vertical position returns the edge row like the old CLAMP_TO_EDGE instead of another row of the atlas) Fonts above 256px, right-to-left text and the web (baked with the browser Canvas2D) are baked as a whole string into one cell like the original. The page policy (append only to the most recently opened page, a new page when it is full, clear the least recently used page beyond 8 pages), the entry limit and the entry key fields (mode, paragraph direction, font string, line width, scale, text) are the same as the original. The original joins the key into a string. Here, to avoid building a string on every lookup, the key is looked up by its hash and the keys inside the same hash are compared one by one.
  • Text is baked in white and the color is multiplied when drawing. (A color change does not rebake) Color glyphs (emoji) are baked in their own color on top of the white text. The original also uploads a canvas filled with fillText in white, so emoji are baked in their own color and the same color is multiplied when drawing. When baking as an outline (Stroke), color glyphs are not stroked and are laid down in their own color. (Same as Chrome strokeText)
  • The font string is read in the same form as Canvas2D font (the CSS font shorthand). Examples: "16px DOSGothic", "bold 24px default", "italic 500 16px default", "12pt 'A B', C, sans-serif" CSS units other than px (ex, ch, cap, ic, lh, rem, including viewport units), named sizes and calc() are read like the Chrome canvas does, and "/line-height" is skipped. For a comma separated name list, each character is looked up starting from the face of the first name. (Same as the browser font list, parse_font_string)
  • As with the original document.fonts, several faces (weight, slant, character range) are registered under one name. (register_font_face) Selection follows the CSS order. When there is no slanted face a fake slant (slope 1/4) is applied per glyph, and when there is no bold face a fake bold is applied per glyph. (textshaping.rs)
  • Characters missing from the faces of the name are looked up in the default font, the system font chain, the standard font (desktop, Chrome's -webkit-standard) and the fallback font, in that order. (The same place as browser font fallback) When no face is found at all in the name list (only unknown names other than default), the standard font is placed before the default font, as Chrome does. The desktop system font chain (set_system_font_chain) is the names of the original SYSTEM_FONT_STRING looked up in the operating system fonts, and it follows the default font only when the default font name default is requested. When enabled, names in the font string that were not uploaded are also looked up in the operating system fonts. A face is read the first time a character of that weight and slant is used. (platform/desktop/systemfont.rs) The fallback font is chosen by the operating system. (set_system_font_fallback_enabled, asking for bold asks for the bold face separately) As in Chrome, it asks separately for the first font (the first face that has the blank) and for each font string, and the fallback face draws only the characters the operating system chose that face for. Characters the face in the name list draws by canonical decomposition (ï as i and U+0308) are not asked. When candidate files are given (add_fallback_font_candidate) they are used first. Candidate files are read when used. For emoji presentation characters a candidate with a color glyph table is read first, and for other characters a candidate without one. (Only the table list is peeked first)
  • When a font face is newly uploaded, only the strings baked with a font string that uses that name and that have a character in the face's character range are discarded. (The original invalidateFontFaces) As in the original this happens only when turned on with set_rebake_text_on_font_load. (The engine turns it on with EngineConfiguration.rebake_text_on_font_load, off by default) When off, text baked with another font before the download stays until it is evicted from the cache. Removing a face and reordering are discarded regardless. Changing the default font or the fallback font discards everything.
  • As in the original, web always bakes and measures with the browser Canvas2D. (platform/web/systemfont.rs) The uploaded font bytes are uploaded to document.fonts as a FontFace and the browser selects and draws. When an uploaded font finishes loading (loadingdone) the baked text is discarded at the start of the frame. Desktop bakes with the shaping and rasterization above.
  • Text anti-aliasing (set_text_antialias_enabled, the original setTextAntialiasEnabled): when off, the alpha of baked text is split into 0 and 255 at the threshold 128 and the texture is sampled with NEAREST. Projects that draw a pixel font at integer multiples of its design size turn it off. The original keeps it as a module global and leaves already baked text alone. Here the cache holds it and puts the on/off state in the key, so text drawn after the change is baked that way right away. (rasterize_text does not take it, like the original ShadowText)
  • Text measuring (measure_text) is not redone when the font string and the text are the same. (The cache of the original measureTextMetrics, 2048 entries) The original discards the least recently used one on each overflow. Here, on overflow the least recently used half is discarded at once. (Searching one by one would scan 2048 entries on every measure after overflow) Registering a font clears it. (The original clears it when a web font finishes loading) Since measure_text takes &self the cache lives in a RefCell.
  • Getting faces on demand (watch_unresolved_family_characters, take_unresolved_family_characters): the original browser downloads an uploaded FontFace when a character in its character range is drawn. The Rust edition collects characters, in measured or baked text of a watched name, that fall outside the range of the uploaded faces, and UIFont takes them out in update and downloads the pieces for those characters.
  • Measuring without a Graphic (measure_text_without_graphic): the original measures text anywhere with a shared 2D canvas. The Rust edition tells a thread-wide global the font list (Rc) every time a font is registered and measures with that list. Used when UI layout needs the number of text lines before drawing. (UIConfirmWindow)

TextEntrystruct traits Clone, Debug

소스source

글 배치 엔트리 하나. (원본 getEntry 의 엔트리, 길이 단위는 모두 논리 픽셀, 베이크 배율로 나눈 값)

  • 문자열을 통째로 구웠을 때의 사각형(quad_width, quad_height, pen_offset_x, baseline_offset_y)과, 그 사각형 왼쪽 위 기준의 글리프 사각형(glyph_textures, glyph_rects)을 준다. 글리프는 글리프 아틀라스에 한 번만 구워 여러 문자열이 나눠 쓴다.
  • 사각형 왼쪽 위는 (펜 x - pen_offset_x, 기준선 y - baseline_offset_y) 에 놓고, 글리프마다 그 자리에 glyph_rects 를 더해 그린다. (Graphic::draw_text_entry)

One text layout entry. (The entry of the original getEntry; all lengths are logical pixels, divided by the bake scale)

  • Gives the rectangle of the string as if baked whole (quad_width, quad_height, pen_offset_x, baseline_offset_y) and the glyph rectangles relative to the top-left of that rectangle (glyph_textures, glyph_rects). Glyphs are baked once into the glyph atlas and shared by many strings.
  • Place the top-left of the rectangle at (pen x - pen_offset_x, baseline y - baseline_offset_y) and draw each glyph by adding glyph_rects to that position. (Graphic::draw_text_entry)
예제Example엔트리의 글리프 사각형을 펜 자리와 기준선에 놓기Placing the entry's glyph rectangles at the pen position and baseline
use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
use vanilla::{Rect, ShapingDirection};

fn calculate_glyph_quads(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext, pen_x: f64, baseline_y: f64) -> Vec<Rect> {
	let Some(entry) = text_string_texture_cache.get_entry(gl, TextDrawKind::Fill, "Score", "24px default", 0.0, 2.0, ShapingDirection::LeftToRight) else {
		return Vec::new();
	};
	let quad_x = pen_x - entry.pen_offset_x;
	let quad_y = baseline_y - entry.baseline_offset_y;
	entry.glyph_rects.iter().map(|glyph_rect| Rect::create(quad_x + glyph_rect[0], quad_y + glyph_rect[1], glyph_rect[2] - glyph_rect[0], glyph_rect[3] - glyph_rect[1])).collect()
}
필드fieldpub glyph_textures: Rc<[crate::core::graphic::GlTexture]>#0.4.0 부터since 0.4.0소스source

글리프마다 든 아틀라스 장 텍스처. (glyph_rects 와 같은 차례, 흰 글자의 프리멀티플라이드 RGBA, 색 글리프는 제 색)

Atlas page texture of each glyph. (Same order as glyph_rects, premultiplied RGBA of white text, color glyphs in their own color)

반환ReturnsRc<[crate::core::graphic::GlTexture]>

필드fieldpub glyph_rects: Rc<[[f64; 8]]>#0.4.0 부터since 0.4.0소스source

글리프 사각형. (문자열 사각형 왼쪽 위 기준 논리 좌표의 왼, 위, 오른, 아래와 아틀라스 텍스처 좌표 u0, v0, u1, v1)

Glyph rectangles. (Left, top, right, bottom in logical coordinates relative to the top-left of the string rectangle, and atlas texture coordinates u0, v0, u1, v1)

반환ReturnsRc<[[f64; 8]]>

필드fieldpub advance_width: f64#0.3.2 부터since 0.3.2소스source

전진폭.

Advance width.

반환Returnsf64

필드fieldpub font_ascent: f64#0.3.2 부터since 0.3.2소스source

글꼴의 기준선 위 길이. (양수)

Font ascent above the baseline. (positive)

반환Returnsf64

필드fieldpub font_descent: f64#0.3.2 부터since 0.3.2소스source

글꼴의 기준선 아래 길이. (양수)

Font descent below the baseline. (positive)

반환Returnsf64

필드fieldpub pen_offset_x: f64#0.3.2 부터since 0.3.2소스source

문자열 사각형 왼쪽에서 펜 원점까지의 거리.

Distance from the left of the string rectangle to the pen origin.

반환Returnsf64

필드fieldpub baseline_offset_y: f64#0.3.2 부터since 0.3.2소스source

문자열 사각형 위에서 기준선까지의 거리.

Distance from the top of the string rectangle to the baseline.

반환Returnsf64

필드fieldpub quad_width: f64#0.3.2 부터since 0.3.2소스source

문자열 사각형 너비. (통째로 구웠을 때의 텍스처 너비를 굽는 배율로 나눈 값)

String rectangle width. (The texture width when baked whole divided by the bake scale)

반환Returnsf64

필드fieldpub quad_height: f64#0.3.2 부터since 0.3.2소스source

문자열 사각형 높이. (통째로 구웠을 때의 텍스처 높이를 굽는 배율로 나눈 값)

String rectangle height. (The texture height when baked whole divided by the bake scale)

반환Returnsf64

TextAtlasStatisticsstruct traits Clone, Copy, Debug, Default, PartialEq, Eq

소스source

글리프 아틀라스 통계. (원본 readAtlasStatistics 의 돌려준 값, 시험과 통계용)

Glyph atlas statistics. (The value returned by the original readAtlasStatistics, for tests and statistics)

예제Example아무것도 굽지 않은 캐시의 통계Statistics of a cache that has baked nothing
use vanilla::core::textstringtexturecache::TextStringTextureCache;

let text_string_texture_cache = TextStringTextureCache::new();
let text_atlas_statistics = text_string_texture_cache.read_atlas_statistics();
assert_eq!(text_atlas_statistics.atlas_page_count, 0);
assert_eq!(text_atlas_statistics.entry_count, 0);
필드fieldpub atlas_page_count: usize#0.4.0 부터since 0.4.0소스source

아틀라스 장 수.

Number of atlas pages.

반환Returnsusize

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

든 글리프 수.

Number of glyphs held.

반환Returnsusize

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

지금까지 구운 글리프 수.

Number of glyphs baked so far.

반환Returnsu64

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

지금까지 아틀라스에 올린 수. (이어 놓은 새 글리프 여럿이 한 번)

Number of uploads to the atlas so far. (Several new glyphs placed next to each other count as one)

반환Returnsu64

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

글 배치 엔트리 수.

Number of text layout entries.

반환Returnsusize

TextRasterstruct traits Clone, Debug

소스source

글 모양 래스터. (덮인 정도 0 ~ 255, 길이 단위는 굽는 배율을 곱한 픽셀)

  • coverage 는 색 글리프를 뺀 글자의 덮인 정도다. 색 글리프(이모지)가 있으면 color_pixels 에 제 색으로 든다. (프리멀티플라이드 RGBA, 같은 크기)

Text shape raster. (coverage 0 ~ 255, lengths in pixels multiplied by the bake scale)

  • coverage is the coverage of the text excluding color glyphs. If there are color glyphs (emoji), they are in color_pixels in their own colors. (premultiplied RGBA, same size)
예제Example글 모양 래스터 받기Get a text shape raster
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;
use vanilla::ShapingDirection;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let text_raster = text_string_texture_cache.rasterize_text("Hi", "20px default", 2.0, 2, ShapingDirection::LeftToRight).expect("raster");
	assert_eq!(text_raster.coverage.len(), (text_raster.width * text_raster.height) as usize);
	assert!(text_raster.origin_x >= 2.0);
	assert!(text_raster.baseline_y > 0.0);
}
필드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 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 there are no color glyphs)

반환ReturnsOption<Vec<u8>>

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

래스터 너비. (픽셀)

Raster width. (pixels)

반환Returnsi32

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

래스터 높이. (픽셀)

Raster height. (pixels)

반환Returnsi32

필드fieldpub origin_x: f64#0.4.0 부터since 0.4.0소스source

래스터 왼쪽에서 펜 원점까지의 거리. (픽셀)

Distance from the left of the raster to the pen origin. (pixels)

반환Returnsf64

필드fieldpub baseline_y: f64#0.4.0 부터since 0.4.0소스source

래스터 위에서 기준선까지의 거리. (픽셀)

Distance from the top of the raster to the baseline. (pixels)

반환Returnsf64

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

전진폭. (픽셀)

Advance width. (pixels)

반환Returnsf64

필드fieldpub font_ascent: f64#0.4.0 부터since 0.4.0소스source

글꼴의 기준선 위 길이. (픽셀, 양수)

Font ascent above the baseline. (pixels, positive)

반환Returnsf64

필드fieldpub font_descent: f64#0.4.0 부터since 0.4.0소스source

글꼴의 기준선 아래 길이. (픽셀, 양수)

Font descent below the baseline. (pixels, positive)

반환Returnsf64

TextMetricsstruct traits Clone, Copy, Debug, Default

소스source

문자열 측정 결과. (Canvas2D TextMetrics)

  • actual_bounding_box_* 는 펜 원점(왼쪽 정렬, 알파벳 기준선)에서 글리프가 실제로 닿는 거리다. (왼쪽, 위, 아래는 그쪽으로 양수)

String measurement result. (Canvas2D TextMetrics)

  • actual_bounding_box_* is the distance glyphs actually reach from the pen origin (left alignment, alphabetic baseline). (left, up and down are positive in their direction)
예제Example글을 재고 실제로 닿는 거리 보기Measure text and check how far it actually reaches
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let text_metrics = text_string_texture_cache.measure_text("20px default", "Hg");
	assert!(text_metrics.width > 0.0);
	assert!(text_metrics.font_ascent > 0.0);
	assert!(text_metrics.actual_bounding_box_ascent > 0.0);
	assert!(text_metrics.actual_bounding_box_descent > 0.0);
}
필드fieldpub width: f64#0.3.2 부터since 0.3.2소스source

전진폭. (픽셀)

Advance width. (pixels)

반환Returnsf64

필드fieldpub font_ascent: f64#0.3.2 부터since 0.3.2소스source

글꼴의 기준선 위 길이. (첫 얼굴의 줄 높이 값, 양수)

Font ascent above the baseline. (line height value of the first face, positive)

반환Returnsf64

필드fieldpub font_descent: f64#0.3.2 부터since 0.3.2소스source

글꼴의 기준선 아래 길이. (첫 얼굴의 줄 높이 값, 양수)

Font descent below the baseline. (line height value of the first face, positive)

반환Returnsf64

필드fieldpub actual_bounding_box_left: f64#0.4.0 부터since 0.4.0소스source

펜 원점에서 글리프 왼쪽 끝까지. (왼쪽이 양수)

From the pen origin to the left edge of the glyphs. (positive to the left)

반환Returnsf64

필드fieldpub actual_bounding_box_right: f64#0.4.0 부터since 0.4.0소스source

펜 원점에서 글리프 오른쪽 끝까지. (오른쪽이 양수)

From the pen origin to the right edge of the glyphs. (positive to the right)

반환Returnsf64

필드fieldpub actual_bounding_box_ascent: f64#0.4.0 부터since 0.4.0소스source

기준선에서 글리프 위 끝까지. (위가 양수)

From the baseline to the top edge of the glyphs. (positive upward)

반환Returnsf64

필드fieldpub actual_bounding_box_descent: f64#0.4.0 부터since 0.4.0소스source

기준선에서 글리프 아래 끝까지. (아래가 양수)

From the baseline to the bottom edge of the glyphs. (positive downward)

반환Returnsf64

FontDescriptionstruct traits Clone, Debug

소스source

폰트 문자열 해석 결과.

  • font_weight 는 CSS 굵기다. ("bold" 700, 숫자, 없으면 400) is_bold 는 굵기가 600 이상인지다.

Font string parse result.

  • font_weight is the CSS weight. ("bold" 700, a number, 400 if none) is_bold is whether the weight is 600 or more.
예제Example폰트 문자열 해석하기Parse a font string
use vanilla::core::textstringtexturecache::parse_font_string;

let font_description = parse_font_string("italic bold 20px \"My Font\", sans-serif");
assert_eq!(font_description.font_size, 20.0);
assert_eq!(font_description.font_weight, 700);
assert!(font_description.is_bold);
assert!(font_description.is_italic);
assert_eq!(font_description.family_name, "My Font");
assert_eq!(font_description.family_name_list, vec!["My Font", "sans-serif"]);
필드fieldpub font_size: f32#0.3.2 부터since 0.3.2소스source

글자 크기. (픽셀)

Font size. (pixels)

반환Returnsf32

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

CSS 굵기. (1 ~ 1000, 없으면 400)

CSS weight. (1 ~ 1000, 400 if none)

반환Returnsu16

필드fieldpub is_bold: bool#0.3.2 부터since 0.3.2소스source

굵기가 600 이상인지.

Whether the weight is 600 or more.

반환Returnsbool

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

italic 이나 oblique 인지.

Whether it is italic or oblique.

반환Returnsbool

필드fieldpub family_name: String#0.3.2 부터since 0.3.2소스source

목록의 첫 이름.

First name in the list.

반환ReturnsString

필드fieldpub family_name_list: Vec<String>#0.4.0 부터since 0.4.0소스source

쉼표로 이은 이름 목록. (앞 이름부터 찾는다)

  • 따옴표 친 이름이 일반 이름(serif, sans-serif, cursive, fantasy, monospace, system-ui, -webkit-body, math)과 같은 글자면 따옴표를 남긴다. ("'monospace'" → "\"monospace\"") 크롬처럼 따옴표 친 것은 그 이름의 글꼴로, 따옴표 없는 것은 일반 이름으로 찾는다.

Comma-separated name list. (looked up from the first name)

  • A quoted name spelled like a generic name (serif, sans-serif, cursive, fantasy, monospace, system-ui, -webkit-body, math) keeps its quotes. ("'monospace'" → "\"monospace\"") Like Chrome, a quoted one is looked up as a font of that name and an unquoted one as the generic name.

반환ReturnsVec<String>

FontFileSourcestruct traits Clone, Debug, PartialEq, Eq

소스source

글꼴 파일 하나의 얼굴. (데스크탑 시스템 글꼴, platform 이 찾아 준다)

  • face_index 를 모르면(맥) post_script_name 으로 모음 안의 얼굴을 찾고, 그것도 없으면 굵기와 기울기로 고른다.

Face of one font file. (desktop system font, found by the platform)

  • If face_index is unknown (Mac), the face in the collection is found by post_script_name, and if that is missing too, chosen by weight and style.
예제Example운영체제가 고른 글꼴 파일을 시스템 글꼴 이름의 얼굴 후보로 더하기Add a font file chosen by the operating system as a face candidate for a system font name
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

let mut text_string_texture_cache = TextStringTextureCache::new();
assert!(!text_string_texture_cache.has_system_font());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	assert!(source.path.exists());
	text_string_texture_cache.add_system_font_candidate("GameSans", 400, false, source);
	assert!(text_string_texture_cache.has_system_font());
}
필드fieldpub path: std::path::PathBuf#0.4.0 부터since 0.4.0소스source

글꼴 파일 경로.

Font file path.

반환Returnsstd::path::PathBuf

필드fieldpub face_index: Option<u32>#0.4.0 부터since 0.4.0소스source

글꼴 모음(TTC) 안의 얼굴 번호. (모르면 None)

Face index within a font collection (TTC). (None if unknown)

반환ReturnsOption<u32>

필드fieldpub post_script_name: Option<String>#0.4.0 부터since 0.4.0소스source

얼굴의 PostScript 이름. (모르면 None)

PostScript name of the face. (None if unknown)

반환ReturnsOption<String>

FamilyFontFacestruct traits Clone, Debug, PartialEq, Eq

소스source

시스템 글꼴 이름이 가진 얼굴 하나. (운영체제가 알려 주는 굵기와 기울임, 얼굴을 고르는 CSS 굵기 규칙의 후보)

One face of a system font name. (the weight and slant the operating system reports, a candidate for the CSS font-weight matching rule that picks a face)

예제Example굵은 얼굴 하나 지어 보기Build one bold face
use vanilla::core::textstringtexturecache::{FamilyFontFace, FontFileSource};

let face = FamilyFontFace {
	source: FontFileSource { path: std::path::PathBuf::from("GameSans-Bold.ttf"), face_index: None, post_script_name: None },
	weight: 700,
	is_italic: false,
};
assert_eq!(face.weight, 700);
필드fieldpub source: FontFileSource#0.4.0 부터since 0.4.0소스source

글꼴 파일과 얼굴.

Font file and face.

반환ReturnsFontFileSource

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

얼굴의 CSS 굵기. (100 ~ 900)

CSS weight of the face. (100 to 900)

반환Returnsu16

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

기울인 얼굴이면 true.

True if the face is slanted.

반환Returnsbool

TextStringTextureCachestruct traits Default

소스source

문자열 텍스처 캐시. (원본 TextStringTextureCache, 글꼴 얼굴 등록, 글 재기, 문자열을 텍스처로 굽기)

  • Graphic 이 하나 든다. (get_text_string_texture_cache) 굽기(get_entry)는 GL 이 있어야 하고, 글꼴 등록과 재기와 래스터는 GL 없이 된다.

String texture cache. (the original TextStringTextureCache, font face registration, text measuring, baking strings into textures)

  • Graphic holds one. (get_text_string_texture_cache) Baking (get_entry) needs GL, while font registration, measuring and rasterizing work without GL.
예제Example글꼴을 올리고 글 재기Register a font and measure text
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

let mut text_string_texture_cache = TextStringTextureCache::new();
assert!(text_string_texture_cache.register_font("GameFont", false, vec![0, 1, 2, 3]).is_err());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	text_string_texture_cache.register_font("GameFont", false, font_bytes).expect("font");
	assert_eq!(text_string_texture_cache.get_font_face_count("gamefont"), 1);
	let text_metrics = text_string_texture_cache.measure_text("20px GameFont", "Hello");
	assert!(text_metrics.width > 0.0);
}
생성자constructorpub fn new() -> TextStringTextureCache#0.3.2 부터since 0.3.2소스source

생성.

Constructor.

반환ReturnsTextStringTextureCache 글꼴도 구운 문자열도 없는 캐시. (안티앨리어싱 켬, 다시 굽기 끔, 웹은 브라우저로 굽는다)A cache with no fonts and no baked strings. (antialiasing on, rebaking off, the web bakes with the browser)

메서드methodpub fn begin_frame(&mut self)#0.3.2 부터since 0.3.2소스source

프레임 시작. (LRU 순서를 프레임 번호로 센다)

Frame start. (counts the LRU order by frame number)

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

브라우저 Canvas2D 로 굽고 재는지. (웹은 원본처럼 늘 참, 데스크탑은 거짓)

Whether it bakes and measures with the browser Canvas2D. (always true on the web as in the original, false on desktop)

반환Returnsbool 웹이면 true, 데스크탑이면 false.True on the web, false on desktop.

메서드methodpub fn register_font(&mut self, family_name: &str, is_bold: bool, font_bytes: Vec<u8>) -> Result<(), String>#0.3.2 부터since 0.3.2소스source

폰트 등록. (폰트 문자열의 이름으로 찾는다. 대소문자 구분 없음, 굵으면 굵기 700 얼굴, 아니면 400)

Registers a font. (looked up by the name in the font string. Case insensitive, a weight 700 face if bold, otherwise 400)

family_name&str
폰트 문자열에서 쓸 이름. (앞뒤 빈칸과 따옴표는 뗀다)Name to use in font strings. (leading and trailing spaces and quotes are removed)
is_boldbool
true 면 굵기 700 얼굴, false 면 400 얼굴.True for a weight 700 face, false for a 400 face.
font_bytesVec<u8>
글꼴 파일 바이트. (ttf, otf, ttc 는 0 번 얼굴, woff, woff2 는 풀어서 읽는다)Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)

반환ReturnsResult<(), String> 올렸으면 Ok. 글꼴을 읽지 못하면 Err(까닭) 이고 아무것도 바뀌지 않는다.Ok if registered. Err(reason) if the font cannot be read, and nothing changes.

메서드methodpub fn register_font_face(&mut self, family_name: &str, font_face_descriptors: FontFaceDescriptors, font_bytes: Vec<u8>) -> Result<(), String>#0.4.0 부터since 0.4.0소스source

글꼴 얼굴 등록. (원본 new FontFace(family, url, descriptors) 를 document.fonts 에 더하기)

  • 같은 이름에 같은 열쇠(source_key), 굵기, 기울기의 얼굴이 있으면 바꾼다. 없으면 맨 뒤(가장 먼저 그리는 자리)에 둔다. set_font_face_order 로 차례를 정한 이름이면 그 차례에 맞춰 놓는다.
  • set_rebake_text_on_font_load 로 켰으면 그 이름을 쓰는 폰트 문자열로 구웠고 이 얼굴의 글자 범위에 든 글자가 있는 문자열은 버린다. (다음에 그릴 때 이 얼굴로 다시 굽는다)

Registers a font face. (the original adding new FontFace(family, url, descriptors) to document.fonts)

  • If the same name has a face with the same key (source_key), weight and style, it is replaced. Otherwise it goes at the end (the slot drawn first). For a name whose order was set with set_font_face_order, it is placed according to that order.
  • If turned on with set_rebake_text_on_font_load, strings baked with font strings using that name and containing characters in this face's character range are dropped. (rebaked with this face on the next draw)
family_name&str
이름. (앞뒤 빈칸과 따옴표는 떼고 대소문자는 가리지 않는다)Name. (leading and trailing spaces and quotes are removed and case is ignored)
font_face_descriptorsFontFaceDescriptors
얼굴의 굵기, 기울기, 글자 범위, 열쇠.Weight, style, character range and key of the face.
font_bytesVec<u8>
글꼴 파일 바이트. (ttf, otf, ttc 는 0 번 얼굴, woff, woff2 는 풀어서 읽는다)Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)

반환ReturnsResult<(), String> 올렸으면 Ok. 글꼴을 읽지 못하면 Err(까닭) 이고 아무것도 바뀌지 않는다.Ok if registered. Err(reason) if the font cannot be read, and nothing changes.

예제Example라틴 글자 범위 얼굴 올리고 지우기Register and remove a Latin character range face
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;
use vanilla::FontFaceDescriptors;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	let mut font_face_descriptors = FontFaceDescriptors::create_from_css("400", "normal", "U+0000-00FF");
	font_face_descriptors.source_key = String::from("latin");
	text_string_texture_cache.register_font_face("GameFont", font_face_descriptors, font_bytes).expect("font");
	assert_eq!(text_string_texture_cache.get_font_face_count("GameFont"), 1);
	assert!(text_string_texture_cache.unregister_font_face("GameFont", "latin"));
	assert_eq!(text_string_texture_cache.get_font_face_count("GameFont"), 0);
}
메서드methodpub fn unregister_font_face(&mut self, family_name: &str, source_key: &str) -> bool#0.4.0 부터since 0.4.0소스source

글꼴 얼굴 지우기. (원본 document.fonts.delete, 열쇠가 같은 얼굴 모두, 지운 것이 있으면 true)

Removes a font face. (the original document.fonts.delete, all faces with the same key, true if any were removed)

family_name&str
이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)Name. (leading and trailing spaces are removed and case is ignored)
source_key&str
지울 얼굴의 열쇠. (FontFaceDescriptors 의 source_key)Key of the face to remove. (source_key of FontFaceDescriptors)

반환Returnsbool 지운 얼굴이 있으면 true.True if any face was removed.

메서드methodpub fn set_font_face_order(&mut self, family_name: &str, source_key_list: &[String])#0.4.0 부터since 0.4.0소스source

한 이름의 얼굴 차례 정하기. (얼굴 열쇠 목록, 뒤가 먼저 그린다. 원본 uifont 가 document.fonts 에서 빼고 차례대로 다시 더하는 것)

  • 목록에 없는 얼굴은 목록의 얼굴보다 뒤로(나중에 그리게) 밀리지 않고 앞에 남는다. 아직 받지 않은 얼굴의 열쇠도 넣어 둘 수 있다. (받으면 그 자리에 놓인다)
  • 차례가 바뀌면 그 이름으로 구운 문자열을 모두 버린다.

Sets the face order of one name. (a list of face keys, later ones draw first. What the original uifont does by removing them from document.fonts and adding them back in order)

  • Faces not in the list are not pushed behind the listed faces (to draw later) and stay in front. Keys of faces not loaded yet can be included too. (placed there once loaded)
  • When the order changes, all strings baked with that name are dropped.
family_name&str
이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)Name. (leading and trailing spaces are removed and case is ignored)
source_key_list&[String]
얼굴 열쇠 목록. (뒤가 먼저 그린다)Face key list. (later ones draw first)
메서드methodpub fn clear(&mut self)#0.4.0 부터since 0.4.0소스source

모든 엔트리와 글리프 버리기. (원본 clear, 아틀라스 장 텍스처는 다음 굽기 때 지운다)

Discards all entries and glyphs. (The original clear; atlas page textures are deleted at the next bake)

메서드methodpub fn set_default_font(&mut self, is_bold: bool, font_bytes: Vec<u8>) -> Result<(), String>#0.3.2 부터since 0.3.2소스source

기본 폰트 설정. (이름을 찾지 못한 폰트 문자열과 글자 대체에 쓴다, 굵으면 굵기 700 얼굴)

Sets the default font. (used for font strings whose name is not found and for character fallback, a weight 700 face if bold)

is_boldbool
true 면 굵기 700 얼굴, false 면 400 얼굴. (같은 굵기의 기울이지 않은 얼굴은 바꾼다)True for a weight 700 face, false for a 400 face. (replaces the non-italic face of the same weight)
font_bytesVec<u8>
글꼴 파일 바이트. (ttf, otf, ttc 는 0 번 얼굴, woff, woff2 는 풀어서 읽는다)Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)

반환ReturnsResult<(), String> 설정했으면 Ok. (구운 문자열은 모두 버린다) 글꼴을 읽지 못하면 Err(까닭).Ok if set. (all baked strings are dropped) Err(reason) if the font cannot be read.

메서드methodpub fn add_fallback_font(&mut self, font_bytes: Vec<u8>) -> Result<(), String>#0.3.2 부터since 0.3.2소스source

대체 폰트 추가. (앞 폰트들에 없는 글자를 찾는다)

Adds a fallback font. (looks up characters missing from the earlier fonts)

font_bytesVec<u8>
글꼴 파일 바이트. (ttf, otf, ttc 는 0 번 얼굴, woff, woff2 는 풀어서 읽는다)Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)

반환ReturnsResult<(), String> 더했으면 Ok. (구운 문자열은 모두 버린다) 글꼴을 읽지 못하면 Err(까닭).Ok if added. (all baked strings are dropped) Err(reason) if the font cannot be read.

메서드methodpub fn set_text_antialias_enabled(&mut self, value: bool)#0.4.0 부터since 0.4.0소스source

글자 안티앨리어싱 켬 / 끔. (원본 setTextAntialiasEnabled, 바꾼 다음 그리는 글자부터 그 방식으로 굽는다)

Turns text antialiasing on / off. (the original setTextAntialiasEnabled, text drawn after the change is baked that way)

valuebool
true 면 켠다. (기본 켬)True to turn it on. (on by default)
메서드methodpub fn is_text_antialias_on(&self) -> bool#0.4.0 부터since 0.4.0소스source

글자 안티앨리어싱이 켜져 있는지. (원본 isTextAntialiasOn)

Whether text antialiasing is on. (the original isTextAntialiasOn)

반환Returnsbool 켜져 있으면 true.true if enabled.

메서드methodpub fn set_rebake_text_on_font_load(&mut self, is_rebake_text_on_font_load: bool)#0.4.0 부터since 0.4.0소스source

글꼴 얼굴을 새로 올리면 그 얼굴의 글자로 구운 문자열을 버릴지 설정. (원본 EngineConfiguration.rebakeTextOnFontLoad, 엔진이 그래픽을 넘겨받을 때 정한다)

Sets whether to drop strings baked with a face's characters when a new font face is registered. (the original EngineConfiguration.rebakeTextOnFontLoad, set when the engine takes over the graphic)

is_rebake_text_on_font_loadbool
true 면 버린다. (기본 끔)True to drop them. (off by default)
메서드methodpub fn get_font_registration_count(&self) -> u64#0.4.0 부터since 0.4.0소스source

글꼴을 등록한 횟수. (등록, 지우기, 차례, 기본 글꼴, 대체 글꼴. 재 둔 글 폭을 다시 잴지 가린다)

Number of times fonts were registered. (registration, removal, order, default font, fallback font. Decides whether cached text widths are measured again)

반환Returnsu64 등록한 횟수. (new 뒤 0 에서 늘기만 한다)Registration count. (only increases from 0 after new)

메서드methodpub fn set_system_font_chain(&mut self, family_name_list: Vec<String>)#0.4.0 부터since 0.4.0소스source

시스템 글꼴 사슬 정하기. (데스크탑, 원본 SYSTEM_FONT_STRING 처럼 기본 글꼴 이름 default 를 청한 폰트 문자열에서 기본 폰트 뒤에 이름 차례로 찾는다)

  • 켜면 폰트 문자열의 올리지 않은 이름도 운영체제 글꼴에서 찾는다. ("16px Arial" 이 시스템의 Arial 로 그려진다, 브라우저와 같다)
  • 얼굴은 그 굵기와 기울기의 글자를 처음 그리거나 잴 때 읽는다.

Sets the system font chain. (Desktop, like the original SYSTEM_FONT_STRING, looked up in name order after the default font for a font string that requests the default font name default)

  • When on, names in the font string that were not uploaded are also looked up in the operating system fonts. ("16px Arial" is drawn with the system Arial, same as the browser)
  • A face is read the first time a character of that weight and slant is drawn or measured.
family_name_listVec<String>
기본 폰트 뒤에 찾을 이름 차례. (대소문자는 가리지 않는다)Order of names to look up after the default font. (case is ignored)
메서드methodpub fn add_system_font_candidate(&mut self, family_name: &str, weight: u16, is_italic: bool, source: FontFileSource)#0.4.0 부터since 0.4.0소스source

시스템 글꼴 이름에 얼굴 후보 파일 더하기. (데스크탑, 그 이름을 사슬 맨 뒤에 둔다. 운영체제에서 찾지 않고 파일을 주는 경우)

  • 얼굴 번호가 없으면 PostScript 이름, 그것도 없으면 청한 굵기와 기울기로 모음 안의 얼굴을 고른다. 가변 글꼴은 굵기를 축 값으로 만든다.

Adds a face candidate file to a system font name. (desktop, puts that name at the end of the chain. For when a file is given instead of searching the operating system)

  • Without a face index, the face in the collection is chosen by PostScript name, and without that, by the requested weight and style. For variable fonts the weight is made from an axis value.
family_name&str
시스템 글꼴 이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)System font name. (leading and trailing spaces are removed and case is ignored)
weightu16
이 후보의 굵기. (CSS 굵기 1 ~ 1000)Weight of this candidate. (CSS weight 1 ~ 1000)
is_italicbool
기울인 얼굴인지.Whether it is an italic face.
sourceFontFileSource
글꼴 파일과 얼굴. (같은 파일, 굵기, 기울기의 후보는 한 번만 든다)Font file and face. (a candidate with the same file, weight and style is held only once)
메서드methodpub fn set_system_font_fallback_enabled(&mut self, value: bool)#0.4.0 부터since 0.4.0소스source

운영체제 대체 글꼴 켬 / 끔. (데스크탑, 켜면 어느 글꼴에도 없는 글자를 운영체제가 고른 글꼴로 그린다. 대체 글꼴 후보 파일이 있으면 그것이 먼저다)

Turns operating system fallback fonts on / off. (desktop, when on, characters missing from every font are drawn with a font chosen by the operating system. Fallback font candidate files come first if any)

valuebool
true 면 켠다. (기본 끔)True to turn it on. (off by default)
메서드methodpub fn has_system_font(&self) -> bool#0.4.0 부터since 0.4.0소스source

시스템 글꼴 사슬이나 후보가 있는지. (데스크탑)

Whether there is a system font chain or candidate. (desktop)

반환Returnsbool 사슬에 찾은 이름이나 후보가 있는 이름이 있거나, 사슬을 켰고 이름이 하나라도 있으면 true.True if the chain has a found name or a name with candidates, or the chain is enabled and has at least one name.

메서드methodpub fn add_fallback_font_candidate(&mut self, font_path: std::path::PathBuf)#0.4.0 부터since 0.4.0소스source

대체 글꼴 후보 파일 더하기. (데스크탑, 원본 브라우저가 글꼴에 없는 글자를 시스템 글꼴로 그리는 자리)

  • 바로 읽지 않는다. 등록된 어느 글꼴에도 없는 글자를 재거나 구울 때 앞의 후보부터 읽어 대체 폰트로 더한다. (큰 한중일 글꼴을 처음에 읽지 않게)
  • 없는 파일, 읽지 못하는 파일은 넘긴다.

Adds a fallback font candidate file. (desktop, where the original browser draws characters missing from fonts with system fonts)

  • Not read right away. When measuring or baking characters missing from every registered font, candidates are read from the front and added as fallback fonts. (so large CJK fonts are not read at startup)
  • Missing or unreadable files are skipped.
font_pathstd::path::PathBuf
글꼴 파일 경로. (더할 때 색 글리프 표가 있는지만 엿본다)Font file path. (only peeks whether it has a color glyph table when added)
메서드methodpub fn has_default_font(&self) -> bool#0.3.2 부터since 0.3.2소스source

기본 폰트가 있는지.

Whether there is a default font.

반환Returnsbool 기본 폰트 얼굴이 하나라도 있으면 true.True if there is at least one default font face.

메서드methodpub fn get_font_face_count(&self, family_name: &str) -> usize#0.4.0 부터since 0.4.0소스source

이름에 올린 얼굴 수. (그 이름이 없으면 0)

Number of faces registered under the name. (0 if the name does not exist)

family_name&str
이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)Name. (leading and trailing spaces are removed and case is ignored)

반환Returnsusize 얼굴 수.Face count.

메서드methodpub fn measure_text(&self, font_string: &str, text: &str) -> TextMetrics#0.3.2 부터since 0.3.2소스source

문자열 측정. (문단 방향은 왼쪽에서 오른쪽, 원본 measureTextMetrics 도 방향을 주지 않는다)

Measures a string. (paragraph direction left to right, the original measureTextMetrics does not take a direction either)

font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)
text&str
잴 글.Text to measure.

반환ReturnsTextMetrics 잰 값. (픽셀) 데스크탑에서 그릴 얼굴이 하나도 없으면 모두 0 이다.Measured values. (pixels) All 0 if there is no face to draw with on desktop.

예제Example같은 글은 한 번만 잰다The same text is measured only once
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let small_metrics = text_string_texture_cache.measure_text("20px default", "abc");
	text_string_texture_cache.measure_text("20px default", "abc");
	assert_eq!(text_string_texture_cache.get_measure_count(), 1);
	let large_metrics = text_string_texture_cache.measure_text("40px default", "abc");
	assert!(large_metrics.width > small_metrics.width);
	assert_eq!(text_string_texture_cache.get_measure_count(), 2);
}
메서드methodpub fn get_measure_count(&self) -> usize#0.4.0 부터since 0.4.0소스source

잰 글 수. (캐시에 든 것, 시험과 통계용)

Number of measured texts. (those in the cache, for tests and statistics)

반환Returnsusize 캐시에 든 잰 글 수. (넘치면 반을 버린다, 상한 2048)Number of measured texts in the cache. (half is dropped on overflow, limit 2048)

메서드methodpub fn get_entry(&mut self, gl: &GlContext, text_draw_kind: TextDrawKind, text: &str, font_string: &str, line_width: f64, bake_scale: f64, direction: ShapingDirection) -> Option<TextEntry>#0.3.2 부터since 0.3.2소스source

글 배치 엔트리 반환. (없으면 배치하고 처음 보는 글리프만 아틀라스에 굽는다, direction 은 문단 방향. 원본 getEntry 의 textDirection)

  • 글리프 아틀라스: 1024 x 1024 장에 글리프를 한 번만 굽는다. 가장 나중에 연 장에만 이어 놓고, 차면 새 장, 8 장을 넘으면 가장 오래 안 쓴 장을 비운다. 비운 장의 텍스처는 버릴 목록에 두고 다음 get_entry 때 지운다. (Graphic 은 쌓아 둔 묶음을 먼저 내보내고 바로 지운다)
  • 글리프 자리는 셰이퍼가 준 자리를 크롬 스키아처럼 정수 자리와 서브픽셀 4 칸으로 나눈다. 글자 덩어리(한글, 숫자 같은 글자는 글자마다, 라틴 낱말은 낱말째)마다 한 칸에 굽는다. 256px 넘는 글꼴과 오른쪽에서 왼쪽 글은 문자열째 굽는다.

Returns a text layout entry. (If missing, lays it out and bakes only glyphs seen for the first time into the atlas; direction is the paragraph direction, textDirection of the original getEntry)

  • Glyph atlas: glyphs are baked once into 1024 x 1024 pages. They are appended only to the most recently opened page, a new page is opened when it is full, and the least recently used page is cleared beyond 8 pages. The texture of a cleared page goes to a discard list and is deleted at the next get_entry. (Graphic flushes the pending batch first and deletes it right away)
  • Glyph positions from the shaper are split into an integer position and 4 subpixel slots like Chrome Skia. Each text chunk (one per character for Hangul, digits and similar, one per word for Latin words) is baked into one cell. Fonts above 256px and right-to-left text are baked as a whole string.
gl&GlContext
텍스처를 만들 GL 컨텍스트.GL context to create the texture with.
text_draw_kindTextDrawKind
굽는 방식.Bake mode.
text&str
구울 글.Text to bake.
font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)
line_widthf64
외곽선 두께. (논리 픽셀, Stroke 로 구울 때만 쓰지만 키에는 늘 든다)Outline width. (logical pixels, used only when baking as Stroke but always part of the key)
bake_scalef64
굽는 배율. (글자 크기에 곱한 크기로 굽고, TextEntry 의 길이는 이것으로 나눈 값이다)Bake scale. (bakes at the text size multiplied by this, and TextEntry lengths are divided by it)
directionShapingDirection
문단 방향.Paragraph direction.

반환ReturnsOption<TextEntry> 글 배치 엔트리. (같은 키면 캐시의 것) 글이 비었거나, 데스크탑에서 그릴 얼굴이 하나도 없거나, 텍스처를 만들지 못하면 None.Text layout entry. (The cached one for the same key) None if the text is empty, there is no face to draw with on desktop, or the texture cannot be created.

예제Example같은 키로 다시 부르면 굽지도 올리지도 않는다Calling again with the same key neither bakes nor uploads
use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
use vanilla::ShapingDirection;

fn bake_outline(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext) {
	text_string_texture_cache.get_entry(gl, TextDrawKind::Stroke, "Hello", "bold 20px default", 3.0, 1.5, ShapingDirection::LeftToRight);
	let first_statistics = text_string_texture_cache.read_atlas_statistics();
	text_string_texture_cache.get_entry(gl, TextDrawKind::Stroke, "Hello", "bold 20px default", 3.0, 1.5, ShapingDirection::LeftToRight);
	assert_eq!(text_string_texture_cache.read_atlas_statistics(), first_statistics);
}
메서드methodpub fn rasterize_text(&self, text: &str, font_string: &str, bake_scale: f64, padding: i32, direction: ShapingDirection) -> Option<TextRaster>#0.4.0 부터since 0.4.0소스source

글의 모양만 래스터로 받기. (텍스처로 올리지 않는다, 그림자를 깐 글처럼 따로 굽는 쪽이 쓴다)

  • 웹은 원본처럼 브라우저 Canvas2D 로 받는다. 데스크탑에서 글꼴이 하나도 없으면 None.

Gets only the text shape as a raster. (not uploaded as a texture, used by those that bake separately, like text with a drop shadow)

  • The web gets it with the browser Canvas2D as in the original. None if there are no fonts at all on desktop.
text&str
글.Text.
font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)
bake_scalef64
굽는 배율. (글자 크기에 곱한다)Bake scale. (multiplied by the text size)
paddingi32
가장자리 여백. (픽셀, 1 보다 작으면 1)Edge padding. (pixels, 1 if less than 1)
directionShapingDirection
문단 방향.Paragraph direction.

반환ReturnsOption<TextRaster> 래스터. 글이 비었거나 데스크탑에서 그릴 얼굴이 하나도 없으면 None.Raster. None if the text is empty or there is no face to draw with on desktop.

메서드methodpub fn rasterize_text_with_color(&self, text: &str, font_string: &str, bake_scale: f64, padding: i32, direction: ShapingDirection, color: Color) -> Option<TextRaster>#0.4.0 부터since 0.4.0소스source

글자 색을 알려 글의 모양만 래스터로 받기. (rasterize_text 와 같고, 맥 데스크탑은 크롬처럼 글자 색 밝기로 덮인 정도를 감마 전보정한다)

  • 원본이 글 색 그대로 Canvas2D 에 굽는 쪽(그림자를 깐 글, 2D 캔버스의 fillText)이 쓴다. 흰색으로 굽고 색을 곱하는 글은 rasterize_text 와 같다.

Get only the shape of the text as a raster, telling the text color. (same as rasterize_text, and the Mac desktop gamma-corrects the coverage by the text color luminance like Chrome)

  • Used by the side the original bakes in the text color into Canvas2D as is (text with a shadow underneath, fillText of the 2D canvas). Text baked white and multiplied by color is the same as rasterize_text.
text&str
글.Text.
font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)
bake_scalef64
굽는 배율. (글자 크기에 곱한다)Bake scale. (multiplied by the text size)
paddingi32
가장자리 여백. (픽셀, 1 보다 작으면 1)Edge padding. (pixels, 1 if less than 1)
directionShapingDirection
문단 방향.Paragraph direction.
colorColor
글자 색. (알파는 쓰지 않는다, 그라데이션이나 패턴으로 칠하면 원본 스키아처럼 회색 0.5)Text color. (alpha is not used; when painting with a gradient or pattern, gray 0.5 like the original Skia)

반환ReturnsOption<TextRaster> 래스터. 글이 비었거나 데스크탑에서 그릴 얼굴이 하나도 없으면 None.Raster. None if the text is empty or there is no face to draw with on desktop.

예제Example검은 글의 덮인 정도 받기Get the coverage of black text
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;
use vanilla::{Color, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, std::fs::read(&source.path).expect("font file")).expect("font");
	let text_raster = text_string_texture_cache.rasterize_text_with_color("Ag", "24px default", 1.0, 2, ShapingDirection::LeftToRight, Color::black()).expect("raster");
	assert_eq!(text_raster.coverage.len(), (text_raster.width * text_raster.height) as usize);
	assert!(text_raster.coverage.iter().any(|value| *value == 255));
}
메서드methodpub fn rasterize_character(&self, character: &str, font_string: &str) -> Option<(textshaping::GlyphRaster, f32, f32, f32)>#0.4.0 부터since 0.4.0소스source

글리프 하나 래스터. (글자 아틀라스가 쓴다, 글리프 번호는 글자로 찾는다. 웹은 브라우저 Canvas2D 로, 데스크탑에서 글꼴이 하나도 없으면 None)

  • 돌려주는 것: (래스터, 전진폭, 글꼴 위 길이, 글꼴 아래 길이) 길이 단위는 픽셀.

Rasterizes one glyph. (used by the glyph atlas, the glyph index is found by character. The web uses the browser Canvas2D, None if there are no fonts at all on desktop)

  • Returns: (raster, advance width, font ascent, font descent) lengths in pixels.
character&str
글자 묶음 하나. (결합 부호가 붙어 여러 글리프가 되어도 한 장에 모은다)One grapheme cluster. (gathered into one image even if combining marks make it several glyphs)
font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)

반환ReturnsOption<(textshaping::GlyphRaster, f32, f32, f32)> (래스터, 전진폭, 글꼴 위 길이, 글꼴 아래 길이). 그릴 글리프가 없으면(빈칸) 빈 래스터. 데스크탑에서 그릴 얼굴이 하나도 없으면 None.(raster, advance width, font ascent, font descent). An empty raster if there are no glyphs to draw (space). None if there is no face to draw with on desktop.

예제Example글자 하나의 래스터와 전진폭Raster and advance width of one character
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let (glyph_raster, advance_width, font_ascent, _) = text_string_texture_cache.rasterize_character("A", "32px default").expect("glyph");
	assert!(glyph_raster.width > 0 && glyph_raster.height > 0);
	assert!(advance_width > 0.0 && font_ascent > 0.0);
	let (space_raster, space_advance_width, _, _) = text_string_texture_cache.rasterize_character(" ", "32px default").expect("space");
	assert_eq!(space_raster.width, 0);
	assert!(space_advance_width > 0.0);
}
메서드methodpub fn get_entry_count(&self) -> usize#0.3.2 부터since 0.3.2소스source

글 배치 엔트리 수.

Number of text layout entries.

반환Returnsusize 캐시에 든 글 배치 엔트리 수. (상한 1024)Number of text layout entries in the cache. (Limit 1024)

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

글리프 아틀라스 통계. (원본 readAtlasStatistics, 시험과 통계용: 장 수, 글리프 수, 지금까지 구운 글리프 수, 지금까지 올린 수, 엔트리 수)

Glyph atlas statistics. (The original readAtlasStatistics, for tests and statistics: page count, glyph count, glyphs baked so far, uploads so far, entry count)

반환ReturnsTextAtlasStatistics 지금의 통계.The current statistics.

예제Example처음 굽는 글은 아틀라스 장을 열고 엔트리 하나를 더한다Text baked for the first time opens an atlas page and adds one entry
use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
use vanilla::ShapingDirection;

fn bake_once(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext) {
	let entry_count = text_string_texture_cache.read_atlas_statistics().entry_count;
	text_string_texture_cache.get_entry(gl, TextDrawKind::Fill, "Score 100", "20px default", 0.0, 1.0, ShapingDirection::LeftToRight);
	let text_atlas_statistics = text_string_texture_cache.read_atlas_statistics();
	assert!(text_atlas_statistics.atlas_page_count >= 1);
	assert!(text_atlas_statistics.baked_glyph_count >= 1);
	assert_eq!(text_atlas_statistics.entry_count, entry_count + 1);
}

함수Functions

함수functionpub fn watch_unresolved_family_characters(family_name: &str)#0.4.0 부터since 0.4.0소스source

이름의 얼굴이 없는 글자 지켜보기 시작. (원본 브라우저는 FontFace 를 document.fonts 에 올려 두면 캔버스가 그 글꼴로 글을 그릴 때 그 글자의 범위에 든 얼굴을 받기 시작한다)

  • 러스트 판은 얼굴을 받은 뒤에 올리므로, 지켜보는 이름으로 재거나 구운 글에서 올린 얼굴의 글자 범위에 들지 않은 글자를 모아 받는 쪽(UIFont)이 꺼내 받는다.

Starts watching characters with no face for a name. (in the original browser, once a FontFace is added to document.fonts, the canvas starts loading the face whose range contains the characters when drawing text with that font)

  • The Rust version registers faces after loading, so it collects characters not in the character ranges of registered faces from text measured or baked with watched names, and the loader (UIFont) takes them out and loads them.
family_name&str
지켜볼 이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)Name to watch. (leading and trailing spaces are removed and case is ignored)
함수functionpub fn take_unresolved_family_characters(family_name: &str) -> String#0.4.0 부터since 0.4.0소스source

지켜보는 이름에서 얼굴이 없던 글자 꺼내기. (꺼내면 비운다, 지켜보지 않는 이름이면 빈 글)

Takes out characters that had no face in watched names. (cleared when taken, empty text if the name is not watched)

family_name&str
지켜보는 이름. (앞뒤 빈칸은 떼고 대소문자는 가리지 않는다)Watched name. (leading and trailing spaces are removed and case is ignored)

반환ReturnsString 모인 글자를 코드 포인트 차례로 이은 글. (빈칸과 제어 글자는 모으지 않는다)Text joining the collected characters in code point order. (spaces and control characters are not collected)

예제Example올린 얼굴이 없는 이름으로 잰 글자 모으기Collect characters measured with a name that has no registered face
use vanilla::core::textstringtexturecache::{take_unresolved_family_characters, watch_unresolved_family_characters, TextStringTextureCache};

watch_unresolved_family_characters("GameFont");
let text_string_texture_cache = TextStringTextureCache::new();
text_string_texture_cache.measure_text("16px GameFont", "b a");
assert_eq!(take_unresolved_family_characters("gamefont"), "ab");
assert_eq!(take_unresolved_family_characters("GameFont"), "");
assert_eq!(take_unresolved_family_characters("OtherFont"), "");
함수functionpub fn measure_normal_line_height_without_graphic(font_string: &str) -> Option<f64>#0.4.0 부터since 0.4.0소스source

Graphic 없이 CSS line-height normal 의 줄 높이 재기. (폰트 문자열, 크롬은 첫째로 쓸 수 있는 글꼴(primary font)의 LineSpacing)

  • 데스크탑은 그릴 때와 같은 얼굴 고르기의 첫 얼굴로 셈한다. (LoadedFont::calculate_normal_line_height) 글꼴이 하나도 없으면 None 이다.
  • 웹은 브라우저가 놓은 줄 높이를 읽는다. (platform/web/systemfont.rs)

Measures the line height of CSS line-height normal without a Graphic. (font string, in Chrome the LineSpacing of the first usable font (primary font))

  • On desktop, computed with the first face of the same face selection as drawing. (LoadedFont::calculate_normal_line_height) None if there are no fonts at all.
  • On the web, reads the line height the browser lays out. (platform/web/systemfont.rs)
font_string&str
Canvas2D font 꼴 글. ("bold 16px sans-serif" 처럼)Text in Canvas2D font form. (like "bold 16px sans-serif")

반환ReturnsOption<f64> 줄 높이. (CSS 픽셀) 데스크탑은 글꼴을 등록한 글자 캐시가 없거나 고를 얼굴이 없으면, 웹은 문서가 없거나 잰 높이가 0 이하면 None.Line height. (CSS pixels) None on desktop if there is no glyph cache with registered fonts or no face to choose, and on the web if there is no document or the measured height is 0 or less.

함수functionpub fn measure_text_without_graphic(font_string: &str, text: &str) -> Option<TextMetrics>#0.4.0 부터since 0.4.0소스source

Graphic 없이 글 재기. (폰트 문자열과 글, 원본의 공용 캔버스 measureText 자리)

  • 그릴 때와 같은 얼굴 고르기와 모양 잇기로 잰다.
  • 웹은 브라우저 Canvas2D 로 잰다. 데스크탑은 글꼴이 하나도 없으면 None 이다. (그릴 때도 글이 나오지 않는 상태)

Measures text without a Graphic. (font string and text, in place of the original shared canvas measureText)

  • Measures with the same face selection and shaping as drawing.
  • The web measures with the browser Canvas2D. Desktop returns None if there are no fonts at all. (a state where no text appears when drawing either)
font_string&str
폰트 문자열. (Canvas2D font 꼴, parse_font_string)Font string. (Canvas2D font form, parse_font_string)
text&str
잴 글.Text to measure.

반환ReturnsOption<TextMetrics> 잰 값. (픽셀) 데스크탑에서 이 스레드에 글꼴을 등록한 캐시가 아직 없거나, 그 폰트 문자열로 고를 얼굴이 하나도 없으면 None.Measured values. (pixels) None on desktop if there is no cache with fonts registered on this thread yet, or no face to choose for that font string.

짝Counterpart: vanilla.js measureTextWithoutGraphic

예제Example글꼴을 등록한 뒤 Graphic 없이 재기Measure without a Graphic after registering a font
use vanilla::core::textstringtexturecache::{measure_text_without_graphic, TextStringTextureCache};
use vanilla::platform::find_fallback_font_file;

assert!(measure_text_without_graphic("16px default", "Hello").is_none());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let text_metrics = measure_text_without_graphic("16px default", "Hello").expect("metrics");
	assert!(text_metrics.width > 0.0);
}
함수functionpub fn parse_font_string(font_string: &str) -> FontDescription#0.3.2 부터since 0.3.2소스source

폰트 문자열 해석. (Canvas2D font 의 CSS font 줄임 꼴, "bold 16px DOSGothic" → 크기 16, 굵기 700, 이름 DOSGothic)

  • 크기 앞의 낱말: normal, italic / oblique(뒤의 각도는 넘긴다)는 기울임, small-caps, 늘이기 낱말(condensed 등)은 넘긴다. bold / bolder 는 700, lighter 는 100, 숫자는 굵기(1 ~ 1000). 그 밖의 낱말이 오면 틀린 문자열이다.
  • 크기: 절대 길이(px, pt, pc, in, cm, mm, q), 글꼴에 대는 길이(em, ex, ch, cap, ic, lh, rem, rex, rch, rcap, ric, rlh), %, 뷰포트 단위, 이름 크기, larger, smaller, calc() 같은 CSS 수학 함수. 뒤의 "/줄높이"는 읽고 넘긴다. (캔버스는 줄높이를 쓰지 않는다) 셈은 parse_css_font_size 가 크롬과 같게 한다. 원본이 글을 굽고 재는 캔버스는 문서에 붙이지 않아 부모 글꼴이 크롬의 마지막 대체 글꼴(맥 Times) 10px 이고, 뿌리는 문서의 표준 글꼴 16px 이다. 웹은 절대 길이 밖의 크기를 브라우저 캔버스에 넣고 다시 읽어 받는다. (platform/web/systemfont.rs 의 resolve_font_size)
  • 크기 뒤는 쉼표로 이은 이름 목록이다. 따옴표 이름은 따옴표를 떼고, 따옴표 없는 이름은 낱말을 빈칸 하나로 잇는다. 그리는 쪽이 목록의 앞 이름부터 찾는다.
  • 틀린 문자열(크기나 이름이 없음, 음수 크기, 모르는 낱말)은 캔버스의 처음 값 "10px sans-serif" 로 본다.

Parses a font string. (the CSS font shorthand of Canvas2D font, "bold 16px DOSGothic" → size 16, weight 700, name DOSGothic)

  • Words before the size: normal, italic / oblique (a following angle is skipped) set italic, small-caps and stretch words (condensed etc.) are skipped. bold / bolder is 700, lighter is 100, numbers are the weight (1 ~ 1000). Any other word makes it an invalid string.
  • Size: absolute lengths (px, pt, pc, in, cm, mm, q), font-relative lengths (em, ex, ch, cap, ic, lh, rem, rex, rch, rcap, ric, rlh), %, viewport units, named sizes, larger, smaller, CSS math functions like calc(). A following "/line-height" is read and skipped. (the canvas does not use line height) parse_css_font_size computes it the same as Chrome. The canvas the original bakes and measures text on is not attached to the document, so the parent font is Chrome's last fallback font (Times on Mac) at 10px, and the root is the document's standard font at 16px. The web gets sizes other than absolute lengths by putting them into a browser canvas and reading them back. (resolve_font_size in platform/web/systemfont.rs)
  • After the size is a comma-separated name list. Quoted names have their quotes removed, unquoted names have their words joined with a single space. The drawing side looks up from the first name in the list.
  • An invalid string (no size or name, negative size, unknown word) is treated as the canvas initial value "10px sans-serif".
font_string&str
폰트 문자열.Font string.

반환ReturnsFontDescription 해석 결과. 틀린 문자열이면 크기 10, 굵기 400, 이름 sans-serif.Parse result. Size 10, weight 400, name sans-serif if the string is invalid.

예제ExampleCSS 단위, 줄높이, 틀린 문자열CSS units, line height, invalid strings
use vanilla::core::textstringtexturecache::parse_font_string;

assert_eq!(parse_font_string("12pt a").font_size, 16.0);
assert_eq!(parse_font_string("1in a").font_size, 96.0);
let line_height_description = parse_font_string("bold 16px/20px a, b");
assert_eq!(line_height_description.font_size, 16.0);
assert_eq!(line_height_description.family_name_list, vec!["a", "b"]);
let invalid_description = parse_font_string("16px");
assert_eq!(invalid_description.font_size, 10.0);
assert_eq!(invalid_description.family_name, "sans-serif");
함수functionpub fn set_font_viewport_size(width: f32, height: f32)#0.4.0 부터since 0.4.0소스source

폰트 문자열의 뷰포트 단위(vw, vh 같은)가 대는 창 크기 정하기. (논리 픽셀, 원본 window.innerWidth / innerHeight 자리. 데스크탑 플랫폼이 창 크기가 바뀔 때 부른다)

Sets the window size that viewport units (vw, vh and such) in font strings refer to. (logical pixels, in place of the original window.innerWidth / innerHeight. The desktop platform calls it when the window size changes)

widthf32
창 너비. (논리 픽셀)Window width. (logical pixels)
heightf32
창 높이. (논리 픽셀)Window height. (logical pixels)

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

소스source

굽는 방식.

Bake mode.

이름Name설명Description
Fill채워 굽기. (원본 fillText)Bake filled. (the original fillText)
Stroke외곽선으로 굽기. (원본 strokeText, 두께는 line_width)Bake as an outline. (the original strokeText, width is line_width)