KMPDFThumbnialPageView.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. //
  2. // KMPDFThumbnialPageView.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2022/11/24.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. class KMPDFThumbnialPageLayer: CATiledLayer {
  10. var page: CPDFPage?
  11. override init() {
  12. super.init()
  13. self.initDefaultValue()
  14. }
  15. required init?(coder: NSCoder) {
  16. super.init(coder: coder)
  17. self.initDefaultValue()
  18. }
  19. public func initDefaultValue() {
  20. self.levelsOfDetail = 2
  21. self.levelsOfDetailBias = 3
  22. self.tileSize = CGSize(width: 1024, height: 1024)
  23. }
  24. override func draw(in ctx: CGContext) {
  25. super.draw(in: ctx)
  26. if (self.page != nil) {
  27. ctx.saveGState();
  28. var bounds = self.page!.bounds
  29. let transform = self.page!.transform()
  30. bounds = bounds.applying(transform);
  31. let viewWidth: CGFloat = NSWidth(self.bounds)
  32. let viewHeight: CGFloat = NSHeight(self.bounds)
  33. if (self.page!.rotation == -90 || self.page!.rotation == -270) {
  34. let height = bounds.size.height
  35. bounds.size.height = bounds.size.width
  36. bounds.size.width = height
  37. }
  38. ctx.scaleBy(x: viewWidth / bounds.size.width,
  39. y: viewHeight / bounds.size.height);
  40. self.page!.drawEdit(with: .cropBox, to: ctx)
  41. ctx.restoreGState();
  42. }
  43. }
  44. }
  45. class KMPDFThumbnialPageView: NSView {
  46. internal var _page: CPDFPage?
  47. var page: CPDFPage? {
  48. get {
  49. self._page
  50. }
  51. set {
  52. self._page = newValue
  53. if pageLayer != nil {
  54. pageLayer.contents = nil
  55. pageLayer.delegate = nil
  56. pageLayer.removeFromSuperlayer()
  57. }
  58. pageLayer = KMPDFThumbnialPageLayer()
  59. pageLayer.frame = self.bounds
  60. pageLayer.page = newValue
  61. self.layer?.addSublayer(pageLayer)
  62. }
  63. }
  64. var pageLayer: KMPDFThumbnialPageLayer!
  65. override init(frame frameRect: NSRect) {
  66. super.init(frame: frameRect)
  67. self.wantsLayer = true
  68. self.layer?.backgroundColor = NSColor.white.cgColor
  69. self.shadow = NSShadow()
  70. self.layer?.shadowColor = NSColor.black.cgColor
  71. self.layer?.shadowOpacity = 0.2
  72. self.layer?.shadowRadius = 3
  73. self.layer?.shadowOffset = CGSize(width: 0, height: -3)
  74. if (pageLayer != nil) {
  75. pageLayer.frame = self.bounds;
  76. }
  77. }
  78. required init?(coder: NSCoder) {
  79. super.init(coder: coder)
  80. }
  81. override func layout() {
  82. super.layout()
  83. if (pageLayer != nil) {
  84. pageLayer.frame = self.bounds;
  85. pageLayer.setNeedsDisplay()
  86. }
  87. }
  88. }