How to subclass NSTextAttachment?

前端 未结 2 1218
-上瘾入骨i
-上瘾入骨i 2020-12-13 07:35

Here is my problem:

I use Core Data to store rich text input from iOS and/or OS X apps and would like images pasted into the NSTextView or UITextView to: a) retain t

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 08:14

    Swift 3 (based on @Bluezen's answer):

    class MyTextAttachment : NSTextAttachment {
    
        override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
    
            guard let image = self.image else {
                return CGRect.zero
            }
    
            let height = lineFrag.size.height
    
            // Scale how you want
            var scalingFactor = CGFloat(0.8)
            let imageSize = image.size
            if height < imageSize.height {
                scalingFactor *= height / imageSize.height
            }
            let rect = CGRect(x: 0, y: 0, width: imageSize.width * scalingFactor, height: imageSize.height * scalingFactor)
    
            return rect
        }
    
    }
    

    Note that I am scaling based on height, as I was getting a lineFrag width value of 10000000 in my particular use case. Also note that I replaced scalingFactor = ... with scalingFactor *= ... so that I could use an additional, non-unity scaling factor (0.8 in this case).

提交回复
热议问题