我用这行代码从非粗体生成粗体:
CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits(currentFont, 0.0, NULL, (wantBold?kCTFontBoldTrait:0), kCTFontBoldTrait);
-
currentFont 是 CTFontRef 我想添加符号特征
-
wantBold 是一个布尔值,用于告诉我是否要在字体中添加或删除粗体特征
-
kCTFontBoldTrait 是我要在字体上修改的符号特征。
第 4 个参数是您要应用的值。第 5 个是选择符号特征的掩码。
你可以把它当作位掩码应用于符号特征,其中CTFontCreateCopyWithSymbolicTraits 的第 4 个参数是值,第 5 个参数是掩码:
[EDIT2]
我终于设法为您的具体情况找到了解决方案:您需要像您已经做的那样获得font 的符号掩码……并按位或与您的@ 符号一起获得987654334@字体。
这是因为 newFontWithoutTraits 实际上 do 具有默认的 symtraits(与我的想法相反,它具有非零 CTFontSymbolicTraits 值),因为 symtraits 值还包含字体类的信息和这样的东西(所以即使是非粗体、非斜体字体也可以有一个非零符号值,记录字体符号的十六进制值以便更好地理解)。
所以这就是你需要的代码:
CTFontRef font = CTFontCreateWithName((CFStringRef)@"Courier Bold", 12, NULL);
CGFloat fontSize = CTFontGetSize(font);
CTFontSymbolicTraits fontTraits = CTFontGetSymbolicTraits(font);
CTFontRef newFontWithoutTraits = CTFontCreateWithName((CFStringRef)@"Arial", fontSize, NULL);
fontTraits |= CTFontGetSymbolicTraits(newFontWithoutTraits);
CTFontRef newFont = CTFontCreateCopyWithSymbolicTraits(newFontWithoutTraits, fontSize, NULL, fontTraits, fontTraits);
// Check the results (yes, this NSLog create leaks as I don't release the CFStrings, but this is just for debugging)
NSLog(@"font:%@, newFontWithoutTraits:%@, newFont:%@", CTFontCopyFullName(font), CTFontCopyFullName(newFontWithoutTraits), CTFontCopyFullName(newFont));
// Clear memory (CoreFoundation "Create Rule", objects needs to be CFRelease'd)
CFRelease(newFont);
CFRelease(newFontWithoutTraits);
CFRelease(font);