2016-08-13 86 views
2

我有NSAttributedString对象与嵌入图像。这些将在NSTextView中提出。在iOS中,我能够调整NSTextAttachment的范围,并且这使得图像适合。在NSTextView中调整图像以适合

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上运行,但它实际上并没有调整图像的大小。下面你可以看到,图像周围有一个正确大小的盒子,但实际的图像溢出了盒子。

enter image description here

我也跟着下面的指南:Implementing Rich Text with Images on OS X and iOS。这将代码移动到子类,但具有相同的效果。

有什么建议吗?除了我应该调整的NSTextAttachment.bounds之外还有什么吗?

UPDATE

我发现,修改的NSImage作品size成分!不过,它现在显示了我所有的图像,但尺寸正确。 :(

+0

如果你想允许用户调整图像大小,我已经创建了一个库来做到这一点:https://github.com/josephessin/ResizableTextAttachment。 –

回答

0

解决!

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)") 
    } 
} 

正如我在更新中提到,您需要更改NSImage.size。翻转是从我在那里留下问题中已链接的子类中来。一旦我回到主要课程,它的作品!