2

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

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

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

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

没有段落间距

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

段落间距 = 32

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

段落间距前 = 32

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

两段,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应该在第二和第三段上方放置空格,我做错了什么?

4

1 回答 1

1

根据我的观察,这种行为仅在您使用以下swift命令时才会出现:

swift YourScript.swift

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

swiftc YourScript.swift && ./YourScript

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

我怀疑您可能需要指定一个选项才能swift使其正常工作,但我找不到swift.

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

swiftc YourScript.swift && ./YourScript
于 2021-02-23T05:12:12.153 回答