調整位於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圖像垂直翻轉。
我不知道什麼可能導致這種垂直翻轉。有沒有辦法來解決這個問題?