Rendering a CGPDFPage into a UIImage

前端 未结 1 355
梦毁少年i
梦毁少年i 2020-12-08 12:36

I\'m trying to render a CGPDFPage (selected from a CGPDFDocument) into a UIImage to display on a view.

I have the following code in MonoTouch which gets me part wa

相关标签:
1条回答
  • 2020-12-08 13:01

    I haven't worked with MonoTouch. However, in objective-C you would get an image for a PDF page like this (notice the CTM transforms):

    -(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;
    
    }
    
    0 讨论(0)
提交回复
热议问题