首页 > 解决方案 > CFAttributedString 改变字体大小没有效果

问题描述

我正在尝试使用 CoreText 和 CoreGraphics 绘制文本。文本绘制和位置很好,但是我似乎无法更改字体大小。或者字体。我尝试直接使用 CFAttributedString 设置属性文本,并尝试更改 CGContext 字体大小设置。这是我的代码

//... (create CGContext)

let textAttrs = [
    kCTFontSizeAttribute as String : 18 as NSNumber
] as CFDictionary

let attrString = CFAttributedStringCreate(kCFAllocatorDefault,
                                          NSString(string: "Hello, world!"),
                                          textAttrs)

let textLine = CTLineCreateWithAttributedString(attrString!)

context.textPosition = CGPoint.zero

CTLineDraw(textLine, context.textPosition)

标签: swiftcore-graphicscore-text

解决方案


问题在于属性的定义。首先我必须定义字体,然后将字体应用为字符串的属性。

let fontAttributes = [
    kCTFontFamilyNameAttribute : "Courier",
    kCTFontStyleNameAttribute : "Bold",
    kCTFontSizeAttribute : 18.0
] as NSDictionary

let descriptor = CTFontDescriptorCreateWithAttributes(fontAttributes)
let font = CTFontCreateWithFontDescriptor(descriptor, 0.0, nil)
let attributes = [kCTFontAttributeName : font] as CFDictionary

let attrString = CFAttributedStringCreate(kCFAllocatorDefault,
                                          "Hello, world!" as NSString,
                                          attributes)

推荐阅读