![](/img/trans.png)
[英]NSTextView or NSTextField automatically resize bounds / frame?
[英]Resize image in NSTextView to fit
我有帶有嵌入圖像的NSAttributedString
對象。 這些將在NSTextView
中呈現。 在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上運行,但實際上不會調整圖像的大小。 在下面可以看到,圖像周圍有一個正確大小的框,但是實際圖像溢出了該框。
我還遵循以下指南: 在OS X和iOS上實現帶有圖像的RTF 。 這會將代碼移至子類,但效果相同。
有什么建議么? 除了NSTextAttachment.bounds
之外,還有其他我應該調整的東西嗎?
UPDATE
我發現修改NSImage
的size
組件有效! 但是,它現在以正確的尺寸顯示了我所有的圖像。 :(
解決了!
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
。 翻轉來自我從問題鏈接中留在其中的一個子類中。 回到主要班級后,它就可以了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.