【发布时间】:2016-08-13 21:51:33
【问题描述】:
我有带有嵌入图像的 NSAttributedString 对象。这些在NSTextViews 中呈现。在 iOS 中,我能够调整 NSTextAttachment 的边界,这使得图像适合。
extension NSTextAttachment {
func setImageWidth(width: CGFloat, range: NSRange) {
var thisImage = image
if thisImage == nil {
thisImage = imageForBounds(bounds, textContainer: nil, characterIndex: range.location)
}
if thisImage != nil {
let ratio = thisImage!.size.height / thisImage!.size.width
bounds = CGRectMake(bounds.origin.x, bounds.origin.y, width, ratio * width)
print("New Bounds: \(bounds)")
}
}
}
此代码也可以在 OSX 上运行,但实际上并不会调整图像大小。下图可以看到,图片周围有一个大小正确的框,但实际图片超出了框。
我还遵循了以下指南:Implementing Rich Text with Images on OS X and iOS。这会将代码移动到子类中,但效果相同。
有什么建议吗?除了NSTextAttachment.bounds,我还有什么需要调整的吗?
更新
我发现修改NSImage 的size 组件有效!但是,它现在显示我所有的图像,但尺寸正确。 :(
【问题讨论】:
-
如果您想允许用户调整图像大小,我已经创建了一个库来做到这一点:github.com/josephessin/ResizableTextAttachment。
标签: macos nstextview nsimage nstextattachment