This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Resize image attachments to fit the view
- Loading branch information
1 parent
9106ef5
commit b3a8994
Showing
3 changed files
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
Sources/AttributedText/NSAttributedString+TextAttachment.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
#if os(macOS) | ||
import AppKit | ||
#elseif canImport(UIKit) | ||
import UIKit | ||
#endif | ||
|
||
extension NSAttributedString { | ||
func updateImageTextAttachments(maxWidth: CGFloat) { | ||
enumerateAttribute(.attachment, in: NSRange(location: 0, length: length), options: []) { value, _, _ in | ||
guard let attachment = value as? NSTextAttachment, | ||
let image = attachment.image else { return } | ||
|
||
let aspectRatio = image.size.width / image.size.height | ||
let width = min(maxWidth, image.size.width) | ||
let height = width / aspectRatio | ||
|
||
attachment.bounds = CGRect(x: 0, y: 0, width: width, height: height) | ||
} | ||
} | ||
} |