Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Resize image attachments to fit the view
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzalezreal committed Dec 20, 2020
1 parent 9106ef5 commit b3a8994
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Sources/AttributedText/AttributedText_AppKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@

override func layout() {
super.layout()

textView.frame = bounds
textView.attributedString().updateImageTextAttachments(maxWidth: bounds.width)
}

override func invalidateIntrinsicContentSize() {
Expand Down
2 changes: 2 additions & 0 deletions Sources/AttributedText/AttributedText_UIKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@

override func layoutSubviews() {
super.layoutSubviews()

textView.frame = bounds
textView.attributedText.updateImageTextAttachments(maxWidth: bounds.width)
}

override func invalidateIntrinsicContentSize() {
Expand Down
20 changes: 20 additions & 0 deletions Sources/AttributedText/NSAttributedString+TextAttachment.swift
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)
}
}
}

0 comments on commit b3a8994

Please sign in to comment.