2016-08-13 85 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。翻轉是從我在那裏留下問題中已鏈接的子類中來。一旦我回到主要課程,它的作品!