从CGPDFPage旋转UIImage

时间:2018-03-06 10:27:08

标签: ios pdf core-graphics

使用https://www.hackingwithswift.com/example-code/core-graphics/how-to-render-a-pdf-to-an-image

中的方法后
func drawPDFfromURL(url: URL) -> UIImage? {

    guard let document = CGPDFDocument(url as CFURL) else { return nil }
    guard let page = document.page(at: 1) else { return nil }

    let pageRect = page.getBoxRect(.mediaBox)

    let renderer = UIGraphicsImageRenderer(size: pageRect.size)
    let img = renderer.image { ctx in

        UIColor.white.set()

        ctx.fill(pageRect)
        ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
        ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

        ctx.cgContext.drawPDFPage(page)
    }

    return img
}

我想使用

直接旋转输出图像
 ctx.rotate(by: 90/180*CGFloat.pi)

但它不起作用。任何帮助都会很明显。

1 个答案:

答案 0 :(得分:0)

在最简单的情况下,生成的图像的宽度应为PDF的高度,图像的高度应为PDF的宽度,因为我们要旋转输出:

Intended rotated output

func drawPDFfromURL(url: URL) -> UIImage? {

    guard let document = CGPDFDocument(url as CFURL) else { return nil }
    guard let page = document.page(at: 1) else { return nil }

    let pageRect = page.getBoxRect(.mediaBox)

    let imageSize = CGSize(width: pageRect.height, height: pageRect.width)
    let imageRect = CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize)
    let renderer = UIGraphicsImageRenderer(size: imageSize)
    let img = renderer.image { ctx in
        UIColor.white.set()

        ctx.fill(imageRect)
        ctx.cgContext.rotate(by:CGFloat.pi / 2)
        ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

        ctx.cgContext.drawPDFPage(page)
    }

    return img
}

此代码给出了以下结果(超级视图的背景为绿色,以便更好地区分生成的图像和白色背景):

Rotated PDF as image

您很可能不希望使用与PDF完全相同的大小值。相反,您可能希望将图像分辨率乘以一个因子。然后代码看起来像这样:

func drawPDFfromURL(url: URL) -> UIImage? {

    guard let document = CGPDFDocument(url as CFURL) else { return nil }
    guard let page = document.page(at: 1) else { return nil }

    let pageRect = page.getBoxRect(.mediaBox)
    let factor: CGFloat = 3.0
    let imageSize = CGSize(width: pageRect.height * factor, height: pageRect.width * factor)
    let imageRect = CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize)
    let renderer = UIGraphicsImageRenderer(size: imageSize)
    let img = renderer.image { ctx in
        UIColor.white.set()

        ctx.fill(imageRect)
        ctx.cgContext.rotate(by:CGFloat.pi / 2)
        ctx.cgContext.scaleBy(x: factor, y: -factor)

        ctx.cgContext.drawPDFPage(page)
    }

    return img
}