【发布时间】:2017-10-10 12:04:18
【问题描述】:
在调整 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)
图像垂直翻转的位置。
我不知道是什么导致了这种垂直翻转。有没有办法解决这个问题?
【问题讨论】:
标签: swift macos cocoa nsattributedstring nsimage