forked from objcio/attributed-string-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwiftUI.swift
37 lines (32 loc) · 1.31 KB
/
SwiftUI.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import Cocoa
import SwiftUI
public struct Embed<V: View>: AttributedStringConvertible {
public init(proposal: ProposedViewSize = .unspecified, @ViewBuilder view: () -> V) {
self.proposal = proposal
self.view = view()
}
var proposal: ProposedViewSize = .unspecified
@ViewBuilder var view: V
@MainActor
public func attributedString(environment: EnvironmentValues) async -> [NSAttributedString] {
let renderer = ImageRenderer(content: view)
renderer.proposedSize = proposal
let resultSize = renderer.nsImage!.size
let data = NSMutableData()
renderer.render { size, renderer in
var mediaBox = CGRect(origin: .zero, size: resultSize)
guard let consumer = CGDataConsumer(data: data),
let pdfContext = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)
else {
return
}
pdfContext.beginPDFPage(nil)
pdfContext.translateBy(x: mediaBox.size.width / 2 - size.width / 2,
y: mediaBox.size.height / 2 - size.height / 2)
renderer(pdfContext)
pdfContext.endPDFPage()
pdfContext.closePDF()
}
return NSImage(data: data as Data)!.attributedString(environment: environment)
}
}