feat(training): 支持课程附件预览与整页阅读
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
import PDFKit
|
||||
import UIKit
|
||||
|
||||
/// 将 PDF 按页面宽度展开为原生绘制视图,由课程页统一负责纵向滚动。
|
||||
@MainActor
|
||||
final class TrainingPDFDocumentView: UIView {
|
||||
/// 当前附件;替换文档时清除旧页面和绘制状态。
|
||||
var document: PDFDocument? {
|
||||
didSet { rebuildPages() }
|
||||
}
|
||||
|
||||
/// 至少一个实际完成绘制的页面进入课程页可见区域。
|
||||
var onVisiblePageDrawn: (() -> Void)?
|
||||
/// 用户点击 PDF 中的 URL 注解,由宿主校验并打开。
|
||||
var onOpenLink: ((URL) -> Void)?
|
||||
/// 按当前宽度排版后的全部页面高度,供宿主更新白色卡片约束。
|
||||
var onContentHeightChange: ((CGFloat) -> Void)?
|
||||
|
||||
private var pageViews: [TrainingPDFPageDrawingView] = []
|
||||
private var contentHeight: CGFloat = 0
|
||||
private var lastLayoutWidth: CGFloat = 0
|
||||
private let pageSpacing: CGFloat = 12
|
||||
|
||||
override var intrinsicContentSize: CGSize {
|
||||
CGSize(width: UIView.noIntrinsicMetric, height: contentHeight)
|
||||
}
|
||||
|
||||
override var isHidden: Bool {
|
||||
didSet { if !isHidden { notifyIfRenderedAndVisible() } }
|
||||
}
|
||||
|
||||
/// 创建不含内部滚动视图的 PDF 页面容器。
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
backgroundColor = .white
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
let width = bounds.width
|
||||
guard width.isFinite, width > 0 else { return }
|
||||
if abs(width - lastLayoutWidth) > 0.5 {
|
||||
lastLayoutWidth = width
|
||||
var offset: CGFloat = 0
|
||||
for page in pageViews {
|
||||
let height = ceil(width * page.heightToWidthRatio)
|
||||
page.frame = CGRect(x: 0, y: offset, width: width, height: height)
|
||||
offset += height + pageSpacing
|
||||
}
|
||||
let height = pageViews.isEmpty ? 0 : offset - pageSpacing
|
||||
updateContentHeight(height)
|
||||
}
|
||||
notifyIfRenderedAndVisible()
|
||||
}
|
||||
|
||||
override func didMoveToWindow() {
|
||||
super.didMoveToWindow()
|
||||
notifyIfRenderedAndVisible()
|
||||
}
|
||||
|
||||
/// 外层滚动、隐藏恢复或布局更新后,确认已绘制内容确实与可见区域相交。
|
||||
func notifyIfRenderedAndVisible() {
|
||||
guard document != nil, pageViews.contains(where: { $0.hasVisibleDrawnTile() }) else { return }
|
||||
onVisiblePageDrawn?()
|
||||
}
|
||||
|
||||
private func rebuildPages() {
|
||||
pageViews.forEach { $0.removeFromSuperview() }
|
||||
pageViews.removeAll()
|
||||
lastLayoutWidth = 0
|
||||
let drawingLock = NSLock()
|
||||
if let document {
|
||||
for index in 0..<document.pageCount {
|
||||
guard let page = document.page(at: index),
|
||||
let pageView = TrainingPDFPageDrawingView(document: document, page: page, drawingLock: drawingLock) else { continue }
|
||||
pageView.onDrawn = { [weak self] in self?.notifyIfRenderedAndVisible() }
|
||||
pageView.onOpenLink = { [weak self] url in self?.onOpenLink?(url) }
|
||||
pageViews.append(pageView)
|
||||
addSubview(pageView)
|
||||
}
|
||||
}
|
||||
if pageViews.isEmpty { updateContentHeight(0) }
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func updateContentHeight(_ height: CGFloat) {
|
||||
guard height.isFinite, abs(contentHeight - height) > 0.5 else { return }
|
||||
contentHeight = height
|
||||
invalidateIntrinsicContentSize()
|
||||
onContentHeightChange?(height)
|
||||
}
|
||||
}
|
||||
|
||||
/// 单页使用分块图层按需绘制,避免将长 PDF 的所有页面预先生成大图。
|
||||
@MainActor
|
||||
private final class TrainingPDFPageDrawingView: UIView {
|
||||
let heightToWidthRatio: CGFloat
|
||||
var onDrawn: (() -> Void)?
|
||||
var onOpenLink: ((URL) -> Void)?
|
||||
private let drawingState: TrainingPDFPageDrawingState
|
||||
private var drawnTiles: [CGRect] = []
|
||||
private var lastDrawingSize: CGSize = .zero
|
||||
|
||||
override class var layerClass: AnyClass { TrainingPDFPageTiledLayer.self }
|
||||
|
||||
init?(document: PDFDocument, page: PDFPage, drawingLock: NSLock) {
|
||||
let transform = page.transform(for: .cropBox)
|
||||
let displayBounds = page.bounds(for: .cropBox).applying(transform).standardized
|
||||
guard displayBounds.width.isFinite, displayBounds.height.isFinite,
|
||||
displayBounds.width > 0, displayBounds.height > 0 else { return nil }
|
||||
heightToWidthRatio = displayBounds.height / displayBounds.width
|
||||
drawingState = TrainingPDFPageDrawingState(document: document, page: page,
|
||||
displayBounds: displayBounds, pageTransform: transform, drawingLock: drawingLock)
|
||||
super.init(frame: .zero)
|
||||
backgroundColor = .white
|
||||
isOpaque = true
|
||||
accessibilityLabel = page.label.map { "PDF 第 \($0) 页" } ?? "PDF 页面"
|
||||
let tiledLayer = layer as! TrainingPDFPageTiledLayer
|
||||
tiledLayer.contentsScale = UIScreen.main.scale
|
||||
tiledLayer.tileSize = CGSize(width: 512, height: 512)
|
||||
tiledLayer.levelsOfDetail = 1
|
||||
tiledLayer.levelsOfDetailBias = 0
|
||||
tiledLayer.needsDisplayOnBoundsChange = true
|
||||
drawingState.onDraw = { [weak self] rect, size in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.bounds.size == size else { return }
|
||||
if !self.drawnTiles.contains(rect) { self.drawnTiles.append(rect) }
|
||||
self.onDrawn?()
|
||||
}
|
||||
}
|
||||
tiledLayer.configure(drawingState)
|
||||
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openLink(_:))))
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
if bounds.size != lastDrawingSize {
|
||||
lastDrawingSize = bounds.size
|
||||
drawnTiles.removeAll()
|
||||
layer.setNeedsDisplay()
|
||||
}
|
||||
}
|
||||
|
||||
func hasVisibleDrawnTile() -> Bool {
|
||||
guard let window, !drawnTiles.isEmpty else { return false }
|
||||
var visible = convert(bounds, to: window).intersection(window.bounds)
|
||||
var ancestor: UIView? = self
|
||||
while let view = ancestor {
|
||||
guard !view.isHidden, view.alpha > 0.01 else { return false }
|
||||
if view.clipsToBounds { visible = visible.intersection(view.convert(view.bounds, to: window)) }
|
||||
guard !visible.isNull, !visible.isEmpty else { return false }
|
||||
ancestor = view.superview
|
||||
}
|
||||
return drawnTiles.contains { !convert($0, to: window).intersection(visible).isEmpty }
|
||||
}
|
||||
|
||||
@objc private func openLink(_ gesture: UITapGestureRecognizer) {
|
||||
guard let url = drawingState.link(at: gesture.location(in: self), size: bounds.size) else { return }
|
||||
onOpenLink?(url)
|
||||
}
|
||||
}
|
||||
|
||||
/// 持有不可变页数据,以文档级锁串行化后台绘制和主线程链接查询。
|
||||
private final class TrainingPDFPageDrawingState: @unchecked Sendable {
|
||||
private let document: PDFDocument
|
||||
private let page: PDFPage
|
||||
private let displayBounds: CGRect
|
||||
private let pageTransform: CGAffineTransform
|
||||
private let drawingLock: NSLock
|
||||
var onDraw: (@Sendable (CGRect, CGSize) -> Void)?
|
||||
|
||||
init(document: PDFDocument, page: PDFPage, displayBounds: CGRect,
|
||||
pageTransform: CGAffineTransform, drawingLock: NSLock) {
|
||||
self.document = document
|
||||
self.page = page
|
||||
self.displayBounds = displayBounds
|
||||
self.pageTransform = pageTransform
|
||||
self.drawingLock = drawingLock
|
||||
}
|
||||
|
||||
func draw(in context: CGContext, bounds: CGRect) {
|
||||
guard bounds.width > 0, bounds.height > 0 else { return }
|
||||
let tile = context.boundingBoxOfClipPath.intersection(bounds)
|
||||
guard !tile.isNull, !tile.isEmpty else { return }
|
||||
drawingLock.lock()
|
||||
context.saveGState()
|
||||
context.setFillColor(UIColor.white.cgColor)
|
||||
context.fill(bounds)
|
||||
let scale = bounds.width / displayBounds.width
|
||||
context.translateBy(x: -displayBounds.minX * scale, y: bounds.height + displayBounds.minY * scale)
|
||||
context.scaleBy(x: scale, y: -scale)
|
||||
page.draw(with: .cropBox, to: context)
|
||||
context.restoreGState()
|
||||
drawingLock.unlock()
|
||||
onDraw?(tile, bounds.size)
|
||||
}
|
||||
|
||||
func link(at point: CGPoint, size: CGSize) -> URL? {
|
||||
guard size.width > 0 else { return nil }
|
||||
drawingLock.lock()
|
||||
defer { drawingLock.unlock() }
|
||||
let scale = size.width / displayBounds.width
|
||||
let displayPoint = CGPoint(x: point.x / scale + displayBounds.minX,
|
||||
y: (size.height - point.y) / scale + displayBounds.minY)
|
||||
let pagePoint = displayPoint.applying(pageTransform.inverted())
|
||||
return page.annotation(at: pagePoint)?.url
|
||||
}
|
||||
}
|
||||
|
||||
/// CATiledLayer 可在后台请求图块;状态快照受锁保护,回调仅返回已绘制的页内矩形。
|
||||
private final class TrainingPDFPageTiledLayer: CATiledLayer {
|
||||
private let stateLock = NSLock()
|
||||
private var state: TrainingPDFPageDrawingState?
|
||||
|
||||
override class func fadeDuration() -> CFTimeInterval { 0 }
|
||||
|
||||
override init() { super.init() }
|
||||
|
||||
override init(layer: Any) {
|
||||
super.init(layer: layer)
|
||||
if let source = layer as? TrainingPDFPageTiledLayer { state = source.snapshot() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
func configure(_ state: TrainingPDFPageDrawingState) {
|
||||
stateLock.lock()
|
||||
self.state = state
|
||||
stateLock.unlock()
|
||||
setNeedsDisplay()
|
||||
}
|
||||
|
||||
override func draw(in context: CGContext) { snapshot()?.draw(in: context, bounds: bounds) }
|
||||
|
||||
private func snapshot() -> TrainingPDFPageDrawingState? {
|
||||
stateLock.lock()
|
||||
defer { stateLock.unlock() }
|
||||
return state
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user