Swift - 使用drawInRect:withAttributes:绘制文本

22

我使用Xcode 6.1 GM遇到了奇怪的问题。

let text: NSString = "A"
let font = NSFont(name: "Helvetica Bold", size: 14.0)

let textRect: NSRect = NSMakeRect(5, 3, 125, 18)
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.LeftTextAlignment
let textColor = NSColor(calibratedRed: 0.147, green: 0.222, blue: 0.162, alpha: 1.0)

let textFontAttributes = [
    NSFontAttributeName: font,
    NSForegroundColorAttributeName: textColor,
    NSParagraphStyleAttributeName: textStyle
]

text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)

错误在行 let texFontAttributes...

Cannot convert the expression's type 'Dictionary' to type 'DictionaryLiteralConvertible'
这段代码在 Xcode 6.1 GM 之前可以完美运行。
当我试图将 textFontAttributes 声明为 NSDictionary 后,错误信息发生了变化:
Cannot convert the expression's type 'NSDictionary' to type 'NSString!'

我不知道怎么解决这个问题 :(


我不知道为什么,但是 drawAtPoint:withAttributes:drawInRect:withAttributes:drawWithRect:options:attributes:sizeWithAttributes:boundingRectWithSize:options:attributes: 在 Swift 中“不可用”。 - JDS
@JDS,这不是在Swift中不可用,而是Swift的String类型不支持。您可以像OP一样在NSString上调用这些方法。 - Blaszard
5个回答

26
问题在于font是可选的,因为方便的构造函数现在返回可选值,所以font需要被解包以成为字典中的一个值:
if let actualFont = font {
    let textFontAttributes = [
        NSFontAttributeName: actualFont,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: textStyle
    ]

    text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}

在Swift中,使用draw in rect绘制文本时,是否可以应用渐变颜色到具有属性的文本上?您可以查看问题 - Kishan Bhatiya

8
在 Swift 4 中,
    let attributeDict: [NSAttributedString.Key : Any] = [
        .font: font!,
        .foregroundColor: textColor,
        .paragraphStyle: textStyle,
    ]

    text.draw(in: rect, withAttributes: attributeDict)

1
现在是 NSAttributedString,Key - Victor Engel
在Swift中,使用draw in rect绘制文本时,是否可以应用渐变颜色到具有属性的文本上?您可以查看问题 - Kishan Bhatiya

2

这也是另一种选择。

let textFontAttributes = [
    NSFontAttributeName : font!,
    NSForegroundColorAttributeName: textColor,
    NSParagraphStyleAttributeName: textStyle
]

1
在XCode 12,Swift 5.3中,我无法找到String对象的draw方法。手动转换为NSString后,它对我起作用了。
let text: String = "XXX"
(text as NSString).draw(in: rect withAttributes: attributes)

0

我在我的应用程序中有这段代码,它可以正常工作:

    var textAttributes: [String: AnyObject] = [
        NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
        NSFontAttributeName : UIFont.systemFontOfSize(17)
    ]

2
在iOS 8中,使用.drawAtPoint:withAttributes方法时,如果传入的是.CGColor会导致崩溃。该方法需要传入一个UIColor对象。 - bitmusher
@bitmusher 谢谢,我的应用程序因为神秘的原因崩溃了,你的评论让我找到了正确的原因。是UIColor,而不是CGColor。你会认为编译器可以捕捉到这个问题,但是从Swift中打包成字符串数组的这些属性有点危险,因为Swift本身非常挑剔和明确。 - DrZ214

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接