vanilladocs
vanillapunch.com
API / platform/desktop/coretextglyph

platform/desktop/coretextglyph

맥 CoreText 글리프 그리기. (macOS 만)

  • 원본에 없는 파일이다. 원본 크롬 맥은 글리프를 CoreText(CoreGraphics)로 그린다. 러스트 판도 맥에서는 글리프를 여기서 CoreText 로 그린다. (textshaping.rs 가 부른다) 색 이모지와 열린 해석기가 읽지 못하는 글꼴은 이 파일만 그릴 수 있다.
  • 색 이모지(sbix, Apple Color Emoji): CoreText 는 작은 글자 크기에서 이모지를 키워 그리고 아래로 내린다. (16px 에서 20px 판, 24px 부터 글자 크기 그대로) 맥 크롬 Canvas2D 의 measureText 로 잰 이모지 전진폭은 CoreText 가 그린 이모지 상자의 높이와 같다. (8px 10, 12px 15, 16px 20, 20px 22, 24px 24, 32px 32, 64px 64) 크롬의 전진폭은 그 상자 높이를 정수로 반올림한 값이다. (13px 의 16.25 는 16, 10px 의 12.5 는 13. 8 ~ 128px 의 23 가지 크기에서 크롬과 같다, 반올림은 textshaping.rs 가 한다) CoreText 의 전진폭(CTFontGetAdvancesForGlyphs)은 글꼴의 자간 표(trak)가 더해져 크롬과 다르므로 쓰지 않는다.
  • 글리프 윤곽이 glyf, CFF, CFF2 어디에도 없는 글꼴: 맥 26 의 PingFangUI.ttc(중국어 대체 글꼴)는 애플 전용 hvgl 표에 윤곽이 있다.
  • 글꼴은 그 얼굴의 PostScript 이름으로 짓는다. (시스템에 올린 글꼴만 CoreText 가 이모지를 키워 그린다) 이름이 점으로 시작하는 숨은 글꼴이거나 축 값을 걸면 파일 경로의 CTFontManagerCreateFontDescriptorsFromURL 서술자를 PostScript 이름(없으면 모음 안의 차례)으로 골라 짓는다. 글자 크기마다 지은 CTFont 는 담아 둔다. (스레드 하나, 넘치면 비운다)
  • 색 글리프 그림은 프리멀티플라이드 RGBA(sRGB) 비트맵 컨텍스트에 흰색으로 그린다. 크롬 캔버스처럼 회색 안티앨리어싱이고 LCD 글자 다듬기는 끈다.
  • 색이 아닌 글리프의 덮인 정도(rasterize_glyph_mask)는 크롬 맥 Canvas2D 와 같은 길로 그린다. 블링크 FontPlatformData::CreateSkFont 는 캔버스 글자에 kSubpixelAntiAlias 와 서브픽셀 자리를 주고, 투명 캔버스는 화소 배열을 모르므로(kUnknown_SkPixelGeometry) 스키아가 LCD 대신 A8 을 LCD 그림에서 뽑는다. 스키아 SkScalerContext_Mac 은 그때 흰 바탕 RGB 비트맵(DeviceRGB, 알파 없음)에 검은 글자를 글꼴 부드럽게(CGContextSetShouldSmoothFonts)를 켜고 칠한 뒤 CoreGraphics 의 감마 2 를 제곱 표로 풀고(gLinearCoverageFromCGLCDValue), 뒤집은 RGB 의 밝기(SkComputeLuminance)를 감마 전보정 표로 고친다. 글리프 상자는 CTFontGetBoundingRectsForGlyphs 에 서브픽셀 몫을 더해 밖으로 반올림하고 사방 1 픽셀을 더한 것이다. (SkScalerContext_Mac::generateMetrics) 가짜 기울임은 스키아처럼 글자 행렬의 기울기(-1/4)로 CoreText 가 그린다.

Mac CoreText glyph drawing. (macOS only)

  • A file not in the original. The original Chrome on Mac draws glyphs with CoreText (CoreGraphics). On the Mac the Rust version also draws glyphs here with CoreText. (called by textshaping.rs) Only this file can draw color emoji and fonts the open parsers cannot read.
  • Color emoji (sbix, Apple Color Emoji): at small text sizes CoreText draws emoji enlarged and lowered. (the 20px version at 16px, the text size as is from 24px) The emoji advance measured with measureText of Mac Chrome Canvas2D equals the height of the emoji box CoreText draws. (8px 10, 12px 15, 16px 20, 20px 22, 24px 24, 32px 32, 64px 64) Chrome's advance is that box height rounded to an integer. (16.25 at 13px is 16, 12.5 at 10px is 13. Matches Chrome at 23 sizes from 8 ~ 128px, textshaping.rs does the rounding) CoreText's advance (CTFontGetAdvancesForGlyphs) adds the font's tracking table (trak) and differs from Chrome, so it is not used.
  • Fonts with glyph outlines in none of glyf, CFF, CFF2: PingFangUI.ttc on Mac 26 (the Chinese fallback font) has its outlines in Apple's private hvgl table.
  • The font is built from that face's PostScript name. (CoreText draws emoji enlarged only for fonts registered in the system) For hidden fonts whose name starts with a dot, or when axis values are set, it builds from the CTFontManagerCreateFontDescriptorsFromURL descriptors of the file path, chosen by PostScript name (or by order within the collection if none). CTFonts built per text size are kept. (one thread, cleared when full)
  • Color glyph pictures are drawn in white into a premultiplied RGBA (sRGB) bitmap context. Grayscale antialiasing like the Chrome canvas, with LCD font smoothing off.
  • The coverage of non-color glyphs (rasterize_glyph_mask) is drawn the same way as Mac Chrome Canvas2D. Blink FontPlatformData::CreateSkFont gives canvas text kSubpixelAntiAlias and subpixel positioning, and since a transparent canvas does not know the pixel layout (kUnknown_SkPixelGeometry), Skia derives A8 from the LCD drawing instead of LCD. Skia SkScalerContext_Mac then draws black text on a white RGB bitmap (DeviceRGB, no alpha) with font smoothing (CGContextSetShouldSmoothFonts) on, undoes the CoreGraphics gamma 2 with a square table (gLinearCoverageFromCGLCDValue), and corrects the luminance of the inverted RGB (SkComputeLuminance) with the gamma pre-correction table. The glyph box is CTFontGetBoundingRectsForGlyphs plus the subpixel part, rounded outward with 1 pixel added on every side. (SkScalerContext_Mac::generateMetrics) Synthetic italic is drawn by CoreText with the text matrix skew (-1/4) like Skia.
예제Example색 이모지 글꼴의 키움 비 재기Measure the enlargement ratio of the color emoji font
use vanilla::platform::desktop::coretextglyph::read_emoji_scale;
use vanilla::platform::find_fallback_font_file;

if let Some(source) = find_fallback_font_file("\u{1F600}", 400, false, true) {
	let emoji_scale = read_emoji_scale(&source.path, source.face_index.unwrap_or(0), 16.0);
	assert!(emoji_scale > 0.0);
}

CoreTextGlyphRasterstruct

소스source

CoreText 로 그린 글리프. (프리멀티플라이드 RGBA, 왼쪽 위 자리는 펜 원점에서 오른쪽 left_x, 기준선에서 위로 top_y)

Glyph drawn with CoreText. (premultiplied RGBA, the top-left position is left_x to the right of the pen origin and top_y up from the baseline)

예제Example시스템 대체 글꼴의 A 글리프 그리기Draw the A glyph of the system fallback font
use std::rc::Rc;
use vanilla::core::textshaping::LoadedFont;
use vanilla::platform::desktop::coretextglyph::{rasterize_glyph, CoreTextGlyphRaster};
use vanilla::platform::find_fallback_font_file;

fn rasterize_character(character: char, pixel_size: f32) -> Option<CoreTextGlyphRaster> {
	let source = find_fallback_font_file(&character.to_string(), 400, false, false)?;
	let face_index = source.face_index.unwrap_or(0);
	let font_bytes: Rc<[u8]> = std::fs::read(&source.path).ok()?.into();
	let loaded_font = LoadedFont::create_from_shared_bytes(font_bytes, face_index, &[]).ok()?;
	let glyph_id = loaded_font.get_shaping_face().glyph_index(character)?;
	rasterize_glyph(&source.path, face_index, glyph_id.0, pixel_size, &[])
}

if let Some(raster) = rasterize_character('A', 32.0) {
	assert_eq!(raster.pixels.len(), (raster.width * raster.height * 4) as usize);
	assert!(raster.top_y > 0);
}
필드fieldpub pixels: Vec<u8>#0.4.0 부터since 0.4.0소스source

픽셀. (프리멀티플라이드 RGBA, 한 줄 width * 4 바이트, 위 줄부터)

Pixels. (premultiplied RGBA, width * 4 bytes per row, top row first)

반환ReturnsVec<u8>

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

가로. (픽셀, 글리프 상자에 사방 1 픽셀을 더한 것)

Width. (pixels, the glyph box plus 1 pixel on every side)

반환Returnsi32

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

세로. (픽셀, 글리프 상자에 사방 1 픽셀을 더한 것)

Height. (pixels, the glyph box plus 1 pixel on every side)

반환Returnsi32

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

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

From the pen origin to the left of the image. (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 image. (pixels, up is positive)

반환Returnsi32

함수Functions

함수functionpub fn read_glyph_bounds(path: &Path, face_index: u32, glyph_index: u16, pixel_size: f32, variation_list: &[(u32, f32)]) -> Option<CGRect>#0.4.0 부터since 0.4.0소스source

글리프가 그려지는 상자. (CTFontGetBoundingRectsForGlyphs, 펜 원점 기준 픽셀, y 는 위가 양수. 그릴 것이 없으면 None)

Box the glyph is drawn in. (CTFontGetBoundingRectsForGlyphs, pixels relative to the pen origin, y is positive upward. None if there is nothing to draw)

path&Path
글꼴 파일 경로.Font file path.
face_indexu32
모음(TTC) 안의 얼굴 번호.Face index within the collection (TTC).
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
variation_list&[(u32, f32)]
가변 글꼴 축 값. ((4 글자 태그의 수, 값) 목록, 비면 축을 걸지 않는다)Variable font axis values. (list of (4-letter tag number, value), no axes are set if empty)

반환ReturnsOption<CGRect> 글리프 상자. CoreText 가 글꼴을 짓지 못했거나 상자의 가로나 세로가 0 이하면 None.Glyph box. None if CoreText could not build the font or the box's width or height is 0 or less.

함수functionpub fn read_glyph_skia_bounds(path: &Path, face_index: u32, glyph_index: u16, pixel_size: f32, variation_list: &[(u32, f32)]) -> Option<CGRect>#0.4.0 부터since 0.4.0소스source

스키아가 짓는 CTFont 의 글리프 상자. (크롬 맥 measureText 의 경로 없는 글리프 상자 셈, 반올림하지 않는다)

  • 스키아 SkScalerContext_Mac 은 글꼴을 SkCTFontCreateExactCopy 로 다시 짓는다. 광학 크기 속성(NSCTFontOpticalSizeAttribute)은 바탕 글꼴의 값이나 글자 크기이고, 자간 속성(NSCTFontUnscaledTrackingAttribute)을 0 으로 두어 trak 과 그 밖의 자간을 끈다. 그 글꼴의 CTFontGetBoundingRectsForGlyphs 다.
  • 색 이모지는 이 글꼴에서 키우기에 따른 자리 밀림이 빠진다. (16px 에서 바탕 글꼴 0.46 ~ 20.46, 스키아 글꼴 0 ~ 20)

Glyph bounds of the CTFont Skia builds. (the glyph-without-path bounds calculation of Mac Chrome measureText; no rounding)

  • Skia SkScalerContext_Mac rebuilds the font with SkCTFontCreateExactCopy. The optical size attribute (NSCTFontOpticalSizeAttribute) is the base font's value or the text size, and the tracking attribute (NSCTFontUnscaledTrackingAttribute) is set to 0 to turn off trak and other tracking. These are CTFontGetBoundingRectsForGlyphs of that font.
  • In this font, color emoji lose the position shift from scaling up. (at 16px, base font 0.46 to 20.46, Skia font 0 to 20)
path&Path
글꼴 파일 경로.Font file path.
face_indexu32
모음(TTC) 안의 얼굴 번호.Face index within the collection (TTC).
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
variation_list&[(u32, f32)]
축 값 목록. ((4 글자 태그의 수, 값))List of axis values. ((the number of the 4-letter tag, value))

반환ReturnsOption<CGRect> 글리프 상자. (펜 원점에서 픽셀, 위가 양수) CoreText 가 글꼴을 짓지 못했거나 상자의 가로나 세로가 0 이하면 None.Glyph bounds. (pixels from the pen origin, up is positive) None when CoreText could not build the font or the bounds width or height is 0 or less.

함수functionpub fn read_emoji_scale(path: &Path, face_index: u32, pixel_size: f32) -> f32#0.4.0 부터since 0.4.0소스source

색 이모지 글꼴을 CoreText 가 키워 그리는 비. (웃는 얼굴 이모지 상자의 높이 / 글자 크기, 재지 못하면 1)

Ratio by which CoreText enlarges color emoji fonts. (smiling face emoji box height / text size, 1 if it cannot be measured)

path&Path
글꼴 파일 경로.Font file path.
face_indexu32
모음(TTC) 안의 얼굴 번호.Face index within the collection (TTC).
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)

반환Returnsf32 이모지 상자 높이를 글자 크기로 나눈 비. (16px 에서 1.25, 24px 부터 1) 글자 크기가 0 이하이거나, 글꼴에 웃는 얼굴이 없거나, 재지 못하면 1.Ratio of the emoji box height divided by the text size. (1.25 at 16px, 1 from 24px) 1 if the text size is 0 or less, the font has no smiling face, or it cannot be measured.

함수functionpub fn rasterize_glyph(path: &Path, face_index: u32, glyph_index: u16, pixel_size: f32, variation_list: &[(u32, f32)]) -> Option<CoreTextGlyphRaster>#0.4.0 부터since 0.4.0소스source

글리프 하나 그리기. (흰색, 색 글리프는 제 색. 그릴 것이 없거나 CoreText 가 읽지 못하면 None)

Draws one glyph. (white, color glyphs in their own colors. None if there is nothing to draw or CoreText cannot read it)

path&Path
글꼴 파일 경로.Font file path.
face_indexu32
모음(TTC) 안의 얼굴 번호.Face index within the collection (TTC).
glyph_indexu16
글리프 번호.Glyph ID.
pixel_sizef32
글자 크기. (픽셀)Font size. (pixels)
variation_list&[(u32, f32)]
가변 글꼴 축 값. ((4 글자 태그의 수, 값) 목록)Variable font axis values. (list of (4-letter tag number, value))

반환ReturnsOption<CoreTextGlyphRaster> 그린 글리프. 그릴 것이 없거나, CoreText 가 글꼴을 짓지 못했거나, 그림이 4096 픽셀을 넘으면 None.The drawn glyph. None if there is nothing to draw, CoreText could not build the font, or the image exceeds 4096 pixels.