iOS PDF文件的读取(UIView 篇)

本文探讨了在iOS应用开发过程中遇到的UIContext无效问题,详细介绍了如何通过在适当位置调用setNeedsDisplay API来解决此问题。文章还提供了一个具体的代码示例,演示了如何使用CGPDFDocumentGetPage、CGPDFPageGetDrawingTransform等API进行PDF页面的绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前在网上查阅了很多资料,大多博客或者论坛都只给出了如何读取的API及代码,如下:

-(void)drawInContext:(CGContextRef)context 

    // PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system 
    // before we start drawing. 
    CGContextTranslateCTM(context, 0.0, self.bounds.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    
    // Grab the first PDF page 
    CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1); 
    // We’re about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing 
    CGContextSaveGState(context); 
    // CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any 
    // base rotations necessary to display the PDF page correctly. 
    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true); 
    // And apply the transform. 
    CGContextConcatCTM(context, pdfTransform); 
    // Finally, we draw the page and restore the graphics state for further manipulations! 
    CGContextDrawPDFPage(context, page); 
    CGContextRestoreGState(context); 
}

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]; 
}


但是,在此需要提醒注意的是:此代码仅能在第一次的时候运行成功,但是如果在进行翻页的时候则可能会出现invaild context 问题,原因则在于,上下文只在绘制UIView时会生成,而当UIView绘制成功之后,再调用UIGraphicsGetCurrentContext() 则获取不到有效上下文,所以需要在适当位置调用以下

API方法:setNeedsDisplay;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值