iphone - 将 CGPDFPage 渲染为 UIImage

标签 iphone ios uiimage xamarin.ios cgpdfdocument

我正在尝试将 CGPDFPage(从 CGPDFDocument 中选择)渲染到 UIImage 中以显示在 View 上。

我在 MonoTouch 中有以下代码,它让我走到了那里。

RectangleF PDFRectangle = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);

    public override void ViewDidLoad ()
    {
        UIGraphics.BeginImageContext(new SizeF(PDFRectangle.Width, PDFRectangle.Height));
        CGContext context = UIGraphics.GetCurrentContext();
        context.SaveState();

        CGPDFDocument pdfDoc = CGPDFDocument.FromFile("test.pdf");
        CGPDFPage pdfPage = pdfDoc.GetPage(1);  

        context.DrawPDFPage(pdfPage);
        UIImage testImage = UIGraphics.GetImageFromCurrentImageContext();

        pdfDoc.Dispose();
        context.RestoreState();

        UIImageView imageView = new UIImageView(testImage);
        UIGraphics.EndImageContext();

        View.AddSubview(imageView);
    }

显示了 CGPDFPage 的一部分,但前后旋转并上下颠倒。我的问题是,如何选择完整的 pdf 页面并将其翻转以正确显示。我看过几个使用 ScaleCTM 和 TranslateCTM 的示例,但似乎无法让它们正常工作。

ObjectiveC 中的任何示例都可以,我会尽我所能获得帮助:)

谢谢

最佳答案

我没有使用过 MonoTouch。但是,在 objective-C 中,您会得到这样的 PDF 页面图像(注意 CTM 转换):

-(UIImage *)getThumbForPage:(int)page_number{
 CGFloat width = 60.0;

    // Get the page
 CGPDFPageRef myPageRef = CGPDFDocumentGetPage(myDocumentRef, page);
 // Changed this line for the line above which is a generic line
 //CGPDFPageRef page = [self getPage:page_number];

 CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
 CGFloat pdfScale = width/pageRect.size.width;
 pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);
 pageRect.origin = CGPointZero;


 UIGraphicsBeginImageContext(pageRect.size);

 CGContextRef context = UIGraphicsGetCurrentContext();

 // White BG
 CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
 CGContextFillRect(context,pageRect);

 CGContextSaveGState(context);

    // ***********
 // Next 3 lines makes the rotations so that the page look in the right direction
    // ***********
 CGContextTranslateCTM(context, 0.0, pageRect.size.height);
 CGContextScaleCTM(context, 1.0, -1.0);
 CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));

 CGContextDrawPDFPage(context, page);
 CGContextRestoreGState(context);

 UIImage *thm = UIGraphicsGetImageFromCurrentImageContext();

 UIGraphicsEndImageContext();
 return thm;

}

关于iphone - 将 CGPDFPage 渲染为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4639781/

相关文章:

iphone - 在 iPhone 的默认照片应用程序的 UIActionSheet 中显示我的应用程序

swift - 将[UInt8]转换为白色透明图像

ios - 如何退出 Facebook

ios - 找不到此可执行文件的有效配置文件错误 Xcode 9

ios - 增强现实-跨叠加对象移动

ios - CoreLocationManager 从不暂停?

ios - 是否可以使用 AVAudioPlayer 和 initWithData :error: to play generated sounds?

iphone - 有没有办法为 UITableViewCell 使用随机项目 png 图像?

ios - 使用 resizeableImageWithCapInsets 平铺 UIImageView :resizingMode?

iphone - 关于在应用程序代码中检查基础 sdk