Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to solve the problem of TTF format fonts generated by allsort not opening on Windows? #108

Closed
bianbiandashen opened this issue Nov 28, 2024 · 0 comments

Comments

@bianbiandashen
Copy link

fn subset_font(
font_data_bytes: &[u8],
text: &str,
) -> Result<Vec, Box> {
use std::collections::HashSet;
use allsorts::binary::read::ReadScope;
use allsorts::font_data::FontData;
use allsorts::subset::subset;
use allsorts::Font;
use allsorts::font::MatchingPresentation;

// 第一次读取字体数据,获取 provider,用于创建 Font 对象
let scope1 = ReadScope::new(font_data_bytes);
let font_data1 = match scope1.read::<FontData<'_>>() {
    Ok(data) => data,
    Err(e) => {
        error!("读取字体数据失败: {:?}", e);
        return Err(Box::new(e));
    }
};
let provider1 = font_data1.table_provider(0)?;

// 创建字体对象
let mut font = Font::new(provider1)?;

// 获取要保留的字形 ID 集合
let mut glyph_ids = HashSet::new();
glyph_ids.insert(0u16); // 始终包含 .notdef 字形

// 临时添加一个中文字符
let mut temp_text = String::from("中");
temp_text.push_str(text);

for ch in temp_text.chars() {
    let (glyph_id, _) = font.lookup_glyph_index(
        ch,
        MatchingPresentation::NotRequired,
        None, // 让编译器自动推断类型
    );
    if glyph_id != 0 {
        glyph_ids.insert(glyph_id);
    } else {
        info!("未找到字形: {},可能是空格或未定义字符", ch);
    }
}

// 将 HashSet<u16> 转换为 Vec<u16>,并排序
let mut glyph_ids_vec: Vec<u16> = glyph_ids.into_iter().collect();
glyph_ids_vec.sort_unstable();

// 第二次读取字体数据,获取新的 provider,用于子集化
let scope2 = ReadScope::new(font_data_bytes);
let font_data2 = scope2.read::<FontData<'_>>()?;
let provider2 = font_data2.table_provider(0)?;

// 调用子集化函数,使用新的 provider2
let subset_font = subset(&provider2, &glyph_ids_vec)?;

if subset_font.is_empty() {
    error!("子集化后的字体数据为空");
} else {
    info!("子集化后的字体数据大小: {} 字节", subset_font.len());
}

Ok(subset_font)

}

@yeslogic yeslogic locked and limited conversation to collaborators Nov 29, 2024
@wezm wezm converted this issue into discussion #109 Nov 29, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant