使用CoreText和CTFontDescriptor设置字体粗细

问题描述 投票:1回答:2

我正在尝试使用CoreText创建具有特定字体粗细的字体。我正在尝试使用通过属性字典创建的CTFontDescriptor来指定字体的名称和字体的粗细。使用了正确的字体系列,但是,权重似乎没有确定。这是我在Swift中的代码:

let fontDescriptorAttributes = [
    kCTFontNameAttribute: "Courier",
    kCTFontTraitsAttribute: [
        kCTFontWeightTrait: NSFont.Weight.black
    ]
] as [CFString : Any]
let fontDescriptor = CTFontDescriptorCreateWithAttributes(fontDescriptorAttributes as CFDictionary)
var identityMat = CGAffineTransform(scaleX: 1.0, y: 1.0)
let font = CTFontCreateWithFontDescriptor(fontDescriptor, 24, &identityMat)

// Use the resulting font with a Core Animation text layer
let textLayer = CATextLayer()
textLayer.font = font
textLayer.string = "foo bar baz!"

textLayer.frame = CGRect(x: 0, y:0, width: textLayer.preferredFrameSize().width, height: textLayer.preferredFrameSize().height)
view.layer.addSublayer(textLayer) // add text layer to view's layer hierarchy

我已经将生成的字体与CATextLayerCFAttributedString一起使用,但是生成的图形均没有正确的字体粗细。我应该设置不同的地方吗?

ios macos core-text typography
2个回答
0
投票

这看起来像是某些字体的iOS / MacOS实现中的错误。我发现Courier和Helvetica字体似乎不接受粗体。但是,大多数其他字体都可以。

例如,使用您的代码,并使用Arial或Times New Roman代替Courier,会产生预期的结果:粗体。

您是否看到过相同的行为?


0
投票

CoreText不合成字体的权重。它不能/不能生成重量的“快递”,如果可以的话,它只能查找一个。

在我的Mac上,Courier具有常规和粗体粗细,但没有黑粗细(使用Font Book.app观察到)。因此,尝试创建Black-weighted Courier变体将不起作用。它只会返回其他权重之一。

因此,您不一定能获得想要的体重。不过,有些技术可以用来使您尽可能接近:

您可以将CTFontDescriptorCreateMatchingFontDescriptors()与指定不足的描述符一起使用(即指定族而不是权重,并枚举结果描述符以找到所需权重的最佳匹配项。

或者,您可以将CTFontDescriptorCreateCopyWithSymbolicTraits()kCTFontTraitBold结合使用以获取字体与粗体最接近的内容。

© www.soinside.com 2019 - 2024. All rights reserved.