Skip to content

Commit 702fc10

Browse files
committed
Scale images to fit the Markdown view
1 parent 721b1f0 commit 702fc10

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Sources/MarkdownUI/Shared/ImageDownloader+TextAttachments.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
let textAttachmentPairs = imageURLs.map { url in
2424
image(for: url).map { image -> (String, NSTextAttachment) in
25-
let attachment = NSTextAttachment()
25+
let attachment = ImageAttachment()
2626
attachment.image = image
2727

2828
return (url.absoluteString, attachment)

0 commit comments

Comments
 (0)