swift - 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)
解决方案
问题在于属性的定义。首先我必须定义字体,然后将字体应用为字符串的属性。
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)
推荐阅读
- r - $后我怎么能帮帮?
- python - 高效地创建与函数对应的字典键值
- python - 将包含许多表的 txt 文件拆分为单个数据框
- ruby-on-rails - 我希望可以仅使用我的帐户创建数据
- javascript - 如何阻止 HighCharts/HighStock 显示日期完全错误的内容?
- javascript - 在本地 localStorage 中存储和重用数据,而不是对 db 进行新调用
- javascript - 为不同的 url 创建一个模板 html
- javascript - Why is fs.createWriteStream throwing a "Error: ENOENT: no such file or directory" error?
- amazon-web-services - AWS CDK - 如何为账户 2 中的服务器部署组提供对账户 1 中我的代码管道的工件存储桶的跨账户访问权限
- virtualbox - Jupyter Notebook and VirtualBox VM sharing the same port (conflict) - how do I change the VM port?