2011-01-09 92 views
5

我想呈现CGPDFPage(从CGPDFDocument中选择)成UIImage显示在视图上。将CGPDFPage呈现为UIImage

我在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任何例子都很好,我会采取所有帮助我能:)

感谢

回答

13

我没有和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; 

} 
+3

很好,谢谢!移植到MonoTouch它看起来像这样https://gist.github.com/771759 – 2011-01-09 15:39:55