I'm currently developing an app and I want to implement a PDF reader on top of UICollectionView.
I am using a custom UIView on each cell which renders the corresponding PDF page:
weak var page: CGPDFPage! {
didSet { setNeedsDisplay() }
}
override func draw(_ rect: CGRect) {
if page == nil {
print("page is nil")
return }
let context = UIGraphicsGetCurrentContext()
context?.clear(bounds)
context?.setFillColor(red: 1, green: 1, blue: 1, alpha: 1)
context?.fill(bounds)
context?.translateBy(x: 0.0, y: bounds.size.height);
context?.scaleBy(x: 1.0, y: -1.0);
var cropBox = page.getBoxRect(.cropBox)
cropBox = CGRect(x: cropBox.origin.x, y: cropBox.origin.y, width: ceil(cropBox.width), height: ceil(cropBox.height))
let scaleFactor = min(bounds.size.width/cropBox.size.width, bounds.size.height/cropBox.size.height)
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
let scaledInnerRect = cropBox.applying(scale)
let translate = CGAffineTransform(translationX: ((bounds.size.width - scaledInnerRect.size.width) / 2) - scaledInnerRect.origin.x, y: ((bounds.size.height - scaledInnerRect.size.height) / 2) - scaledInnerRect.origin.y)
let concat = translate.scaledBy(x: scaleFactor, y: scaleFactor)
context?.concatenate(concat)
let clipRect = cropBox
context?.addRect(clipRect)
context?.clip()
context?.drawPDFPage(page)
UIGraphicsEndPDFContext()
}
So far so good. It renders the page on the cell but it causes a memory problem.
Somehow the context keeps a reference to all the pages rendered on the cells of the collection view and they are not getting deallocated. CGPDFPageRelease is no longer available. :(
On the other hand, if this uiview subclass is zoomed inside a scrollview how can I redraw the pdf so I don't loose quality?
Any help will be highly appreciated. Thank you!