[英]Resize image in NSTextView to fit
I have NSAttributedString
objects with embedded images. 我有带有嵌入图像的
NSAttributedString
对象。 These are being presented in NSTextView
s. 这些将在
NSTextView
中呈现。 In iOS, I was able to resize the bounds of NSTextAttachment
, and this makes the image fit. 在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)")
}
}
}
This code also runs on OSX, but it does not actually resize the image. 该代码也可以在OSX上运行,但实际上不会调整图像的大小。 Below you can see, there is a box of the correct size around the image, but the actual image overflows the box.
在下面可以看到,图像周围有一个正确大小的框,但是实际图像溢出了该框。
I have also followed the following guide: Implementing Rich Text with Images on OS X and iOS . 我还遵循以下指南: 在OS X和iOS上实现带有图像的RTF 。 This moves the code to subclasses, but has the same effect.
这会将代码移至子类,但效果相同。
Any suggestions? 有什么建议么? Is there something besides
NSTextAttachment.bounds
that I should be adjusting? 除了
NSTextAttachment.bounds
之外,还有其他我应该调整的东西吗?
UPDATE UPDATE
I found that modifying the size
component of NSImage
works! 我发现修改
NSImage
的size
组件有效! However, it is now showing all my images upside, but at the correct size. 但是,它现在以正确的尺寸显示了我所有的图像。 :(
:(
Solved! 解决了!
extension NSImage {
func resizeToFit(containerWidth: CGFloat) {
var scaleFactor : CGFloat = 1.0
let currentWidth = self.size.width
let currentHeight = self.size.height
if currentWidth > containerWidth {
scaleFactor = (containerWidth * 0.9) / currentWidth
}
let newWidth = currentWidth * scaleFactor
let newHeight = currentHeight * scaleFactor
self.size = NSSize(width: newWidth, height: newHeight)
print("Size: \(size)")
}
}
As I mentioned in the update, you need to change the NSImage.size
. 正如我在更新中提到的那样,您需要更改
NSImage.size
。 The flip was coming from one of the subclasses I had left in there from the link in the question. 翻转来自我从问题链接中留在其中的一个子类中。 Once I went back to the main classes, it works!
回到主要班级后,它就可以了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.