我正在 macOS 上编写一个从文本创建图像的命令行脚本。我想在上面给一些段落额外的空间, 以将它们与上一段分开。由于脚本的工作方式,在段落上设置额外空间的属性会更容易,而不是更改前一段的属性。我认为这就是paraSpacingBefore的NSMutableParagraphStyle
用途。
但是,虽然我可以让 paragraphSpacing 在第一段之后提供空间,但 paragraphSpacingBefore 似乎在第二段之后添加空间。
这个非常简化的测试脚本将创建一个包含三个段落的图像。
将paragraphSpacing
行和paragraphSpacingBefore
行都注释掉后,段落之间或段落周围没有额外的间距:
如果该paragraphSpacing
行未注释,则三个段落之间有空格:
但是如果该paragraphSpacing
行被注释掉并且该paragraphSpacingBefore
行被取消注释,则三段之间没有空格但在第三段之后添加了空格:
看起来末尾的间距是paragraphSpacingBefore值的两倍;如果我注释掉该cheers +=
行以使其只有两个段落,则最后一段之后的空间看起来大约减半:
这对我来说没有意义。我希望第三张图片(paragraphSpacingBefore
过去与第二张图片非常相似。我误解了这paragraphSpacingBefore
意味着什么,和/或我做错了什么。
#!/usr/bin/swift
//test paragraphSpacingBefore
import AppKit
//set up text
var cheers = "“What do you say, Norm?”\nAny cheap, tawdry thing that’ll get me a beer."
cheers += "\n—Cheers"
var paragraphStyle = NSMutableParagraphStyle()
//paragraphStyle.paragraphSpacing = 32
paragraphStyle.paragraphSpacingBefore = 32
var textAttributes = [NSAttributedString.Key.paragraphStyle:paragraphStyle]
let textLines = NSAttributedString(string:cheers, attributes:textAttributes)
//create image of text
let outputSize = textLines.size()
let textRect = NSRect(x: 0, y: 0, width: outputSize.width, height: outputSize.height)
let background = NSColor(red:0, green:1, blue:1, alpha:1)
let outputImage = NSImage(size:outputSize, flipped: false) { (outputRect) -> Bool in
//set a background color
background.setFill()
outputRect.fill()
//draw the text
textLines.draw(in: textRect)
return true
}
//save image to file
var imageData = outputImage.tiffRepresentation
let bitmappedText = NSBitmapImageRep(data: imageData!)
imageData = bitmappedText!.representation(using: NSBitmapImageRep.FileType.png, properties:[:])
do {
try imageData!.write(to: NSURL.fileURL(withPath: "norm.png"))
} catch {
print("Unable to save file.")
}
如果paragraphSpacingBefore
应该在第二和第三段上方放置空格,我做错了什么?