Ios 强制PDF页面填充上下文
在我的项目中,我确实需要生成一个用CoreGraphics生成的PDF页面的图像 我设法用我想要的图像大小创建了一个上下文(Ios 强制PDF页面填充上下文,ios,swift,pdf,core-graphics,Ios,Swift,Pdf,Core Graphics,在我的项目中,我确实需要生成一个用CoreGraphics生成的PDF页面的图像 我设法用我想要的图像大小创建了一个上下文(destinationSize:CGSize),但当我使用CGPDFPageGetDrawingTransform函数时,它只会向下调整页面大小,但不会缩放上下文以使页面填充目标矩形 以下是我目前在项目中的代码摘录: UIGraphicsBeginImageContextWithOptions(destinationSize, true, 0) defer { U
destinationSize:CGSize
),但当我使用CGPDFPageGetDrawingTransform
函数时,它只会向下调整页面大小,但不会缩放上下文以使页面填充目标矩形
以下是我目前在项目中的代码摘录:
UIGraphicsBeginImageContextWithOptions(destinationSize, true, 0)
defer {
UIGraphicsEndImageContext()
}
// Invert y axis (CoreGraphics and UIKit axes are differents)
CGContextTranslateCTM( ctx, 0, destinationSize.height);
CGContextScaleCTM(ctx, 1, -1)
let transform = CGPDFPageGetDrawingTransform(pageRef, .CropBox, CGRect(origin: CGPointZero, size: destinationSize), 0, true)
CGContextConcatCTM(ctx, transform)
// TODO We need force the page to fill all the dest rect when it's bigger than the CropBox size
CGContextDrawPDFPage(ctx, pageRef)
我试着用这个来代替TODO,用一个比例因子来缩放我的上下文:
let contextScale: CGFloat = (pageRect.width < expectedWidth) ? expectedWidth / pageRect.width : 1
CGContextScaleCTM(ctx, contextScale, contextScale)
let contextScale:CGFloat=(pageRect.width
但它创建了一个不正确的图形偏移量,我对CoreGraphics变换有点迷茫
重新缩放上下文以确保pdf页面绘制以填充上下文大小的正确方法是什么?这是我提出的解决方案 据我所知,这适用于任何pdf文档页面。(通过多次旋转、cropbox尺寸和原点进行测试
func transformationForPage(_ pageNumber: Int, targetSize: CGSize) -> CGAffineTransform {
let pageRef = getPage(pageNumber)
let rotation = getPageRotationInteger(pageNumber)
let cropbox = cropboxForPage(pageNumber)
var transform = pageRef!.getDrawingTransform(.cropBox, rect: CGRect(origin: CGPoint.zero, size: targetSize), rotate: 0, preserveAspectRatio: true)
// We change the context scale to fill completely the destination size
if cropbox.width < targetSize.width {
let contextScale = targetSize.width / cropbox.width
transform = transform.scaledBy(x: contextScale, y: contextScale)
transform.tx = -(cropbox.origin.x * transform.a + cropbox.origin.y * transform.b)
transform.ty = -(cropbox.origin.x * transform.c + cropbox.origin.y * transform.d)
// Rotation handling
if rotation == 180 || rotation == 270 {
transform.tx += targetSize.width
}
if rotation == 90 || rotation == 180 {
transform.ty += targetSize.height
}
}
return transform
}
func transformationForPage(\uPageNumber:Int,targetSize:CGSize)->cGraffinetTransform{
让pageRef=getPage(页码)
let rotation=GetPageRotationIntegrater(页码)
设cropbox=cropboxFormage(页码)
var transform=pageRef!.getDrawingTransform(.cropBox,rect:CGRect(原点:CGPoint.zero,大小:targetSize),旋转:0,保留AspectRatio:true)
//我们更改上下文比例以完全填充目标大小
如果cropbox.width