|
| 1 | +#if !os(watchOS) |
| 2 | + |
| 3 | + #if os(macOS) |
| 4 | + import AppKit |
| 5 | + #elseif canImport(UIKit) |
| 6 | + import UIKit |
| 7 | + #endif |
| 8 | + |
| 9 | + final class ImageAttachment: NSTextAttachment { |
| 10 | + #if os(macOS) |
| 11 | + override func attachmentBounds( |
| 12 | + for textContainer: NSTextContainer?, |
| 13 | + proposedLineFragment lineFrag: NSRect, |
| 14 | + glyphPosition position: CGPoint, |
| 15 | + characterIndex charIndex: Int |
| 16 | + ) -> NSRect { |
| 17 | + guard let image = self.image else { |
| 18 | + return super.attachmentBounds( |
| 19 | + for: textContainer, |
| 20 | + proposedLineFragment: lineFrag, |
| 21 | + glyphPosition: position, |
| 22 | + characterIndex: charIndex |
| 23 | + ) |
| 24 | + } |
| 25 | + |
| 26 | + let aspectRatio = image.size.width / image.size.height |
| 27 | + let width = min(lineFrag.width, image.size.width) |
| 28 | + let height = width / aspectRatio |
| 29 | + |
| 30 | + return NSRect(x: 0, y: 0, width: width, height: height) |
| 31 | + } |
| 32 | + #else |
| 33 | + override func attachmentBounds( |
| 34 | + for textContainer: NSTextContainer?, |
| 35 | + proposedLineFragment lineFrag: CGRect, |
| 36 | + glyphPosition position: CGPoint, |
| 37 | + characterIndex charIndex: Int |
| 38 | + ) -> CGRect { |
| 39 | + guard let image = self.image else { |
| 40 | + return super.attachmentBounds( |
| 41 | + for: textContainer, |
| 42 | + proposedLineFragment: lineFrag, |
| 43 | + glyphPosition: position, |
| 44 | + characterIndex: charIndex |
| 45 | + ) |
| 46 | + } |
| 47 | + |
| 48 | + let aspectRatio = image.size.width / image.size.height |
| 49 | + let width = min(lineFrag.width, image.size.width) |
| 50 | + let height = width / aspectRatio |
| 51 | + |
| 52 | + return CGRect(x: 0, y: 0, width: width, height: height) |
| 53 | + } |
| 54 | + #endif |
| 55 | + } |
| 56 | + |
| 57 | +#endif |
0 commit comments