gpt4 book ai didi

swift - 添加到 NSAttributedString 时翻转图像

转载 作者:行者123 更新时间:2023-11-28 08:01:08 27 4
gpt4 key购买 nike

在调整 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)

图像垂直翻转的位置。

我不知道是什么导致了这种垂直翻转。有办法解决这个问题吗?

最佳答案

如果您查看 NSTextAttachment 的开发者文档:

https://developer.apple.com/documentation/uikit/nstextattachment

bounds参数定义如下:

“定义文本坐标系中接收器图形表示的布局边界。”

我知道在使用 CoreText 布局文本时,您需要翻转坐标,所以我想您也需要将 bounds 参数转换为垂直反射。

希望对您有所帮助。

关于swift - 添加到 NSAttributedString 时翻转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com