I'm trying to draw a PDFPage
onto the context of a UIView
subclass:
class PDFPageView: UIView {
private let page: PDFPage
init(frame: CGRect, page: PDFPage) {
self.page = page
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
// This scales the page correctly (ignoring aspect ratios for now, though)
let bounds = page.bounds(for: .mediaBox)
context.scaleBy(x: rect.width / bounds.width, y: rect.height / bounds.height)
// This has no effect when I use it (?)
// page.transform(context, for: .mediaBox)
page.draw(with: .mediaBox, to: context)
}
}
It is drawing something, but it is mirrored (vertically) and I don't know how to correct this. I thought page.transform(context, for: .mediaBox)
should do everything so that the context renders the page correctly. But it does nothing, strangely.
I tried to manually set the scale. It's working, but only for positive values. If I try to set a negative x-scale or y-scale (to compensate for the mirroring) I only get a black screen on my device.
I'm not sure what I should do. Also, it is only working for some pdf. I wanted to show you a screenshot so I created a small pdf file (the ones I use for testing are copyrighted, I think) and loaded it into the app. But I only get a black screen her as well.
I'd really appreciate any help with this.
Thank you
EDIT: Okay, I got it kind of working. After scaling the y-axis by a negative value, I need to translate the context using context.translateBy(x: 0, y: rect.height)
. Then it's rendered correctly.
But still, why is page.transform(context, for: .mediaBox)
not doing this? And is vertically flipping the context valid for every pdf page?