NSMutableParagraphStyle.paragraphSpacingBefore 是否应该在段落前添加空格?

问题描述

我正在 macOS 上编写一个命令行脚本,用于从文本创建图像。我想给一些段落额外的空间above,以将它们与上一段分开。由于脚本的工作方式,在段落上设置属性以在其上方放置额外空间会更容易,而不是更改上一段的属性。我以为这就是 NSMutableParagraphStyle 上的 paragraphSpacingBefore 的用途。

然而,虽然我可以让paragraphSpacing在第一段之后提供空间,但paragraphSpacingBefore似乎在第二段之后添加了空间。

这个非常简单的测试脚本将创建一个包含三个段落的图像。

paragraphSpacing 行和 paragraphSpacingBefore 行都注释掉后,段落之间或段落周围没有添加额外的间距:

no paragraph spacing

如果 paragraphSpacing 行没有注释,则三个段落之间有空格:

paragraphSpacing = 32

但是如果 paragraphSpacing 行被注释掉,而 paragraphSpacingBefore 行没有被注释,则三段之间没有空格,但在第三段之后添加了空格:

paragraphSpacingBefore = 32

看起来末尾的间距是paragraphSpacingBefore值的两倍;如果我注释掉 cheers += 行使其只有两段,则最后一段之后的空间看起来大约减半:

two paragraphs,paragraphSpacingBefore = 32

这对我来说没有意义。我希望第三张图片(使用 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 应该在第二和第三段上方放置空格,我做错了什么?

解决方法

据我观察,此行为仅在您使用 swift 命令时出现:

swift YourScript.swift

如果您改为在 Xcode“命令行工具”项目中运行代码,或者在 Xcode 游乐场中运行代码,或者使用 swiftc 编译代码,然后运行它,

swiftc YourScript.swift && ./YourScript

paragraphSpacingBefore 正确地将间距放在正确的位置。

我怀疑您可能需要为 swift 指定一个选项才能使其工作,但我找不到 swift 独有的相关选项。

所以现在的解决方法是编写一个新的 bash/zsh 脚本来运行:

swiftc YourScript.swift && ./YourScript