添加到NSAttributedString时翻转图像
问题描述:
调整位于NSAttributedString中的图像时,出现奇怪的问题。调整大小的扩展工作正常,但是当图像被添加到NSAttributedString时,出于某种原因它会垂直翻转。添加到NSAttributedString时翻转图像
这是伸缩扩展:
extension NSImage {
func resize(containerWidth: CGFloat) -> NSImage {
var scale : CGFloat = 1.0
let currentWidth = self.size.width
let currentHeight = self.size.height
if currentWidth > containerWidth {
scale = (containerWidth * 0.9)/currentWidth
}
let newWidth = currentWidth * scale
let newHeight = currentHeight * scale
self.size = NSSize(width: newWidth, height: newHeight)
return self
}
}
这里是属性串枚举在图像上:
newAttributedString.enumerateAttribute(NSAttributedStringKey.attachment, in: NSMakeRange(0, newAttributedString.length), options: []) { value, range, stop in
if let attachement = value as? NSTextAttachment {
let image = attachement.image(forBounds: attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)!
let newImage = image.resize(containerWidth: markdown.bounds.width)
let newAttribute = NSTextAttachment()
newAttribute.image = newImage
newAttributedString.addAttribute(NSAttributedStringKey.attachment, value: newAttribute, range: range)
}
}
我已经设置断点和检查图像,他们是全部在正确的旋转中,除了当它到达这条线时:
newAttributedString.addAttribute(NSAttributedStringKey.attachment, value: newAttribute, range: range)
wh图像垂直翻转。
我不知道什么可能导致这种垂直翻转。有没有办法来解决这个问题?
答
我想通了,它比我做得更简单。
由于图像是在一个NSAttribuetdString被追加到NSTextView我并不需要在NSAttributedString来调整每个图像,而我不得不设置NSTextView中的附件缩放与
markdown.layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown
一行是所有花了
答
如果你看看开发人员文件NSTextAttachment:
https://developer.apple.com/documentation/uikit/nstextattachment
bounds参数的定义如下:
“定义接收器的图形表示的布局界限文本坐标系。“
我知道,当使用CoreText来布局文本时,您需要翻转坐标,所以我应该想象您需要将垂直边界参数转换为垂直坐标也反映。
希望有所帮助。