1
我想爲PDF文檔中的每個PDF頁面創建縮略圖並將其放置在UISCrollVIew中。我在這方面取得了成功,但當速度太快時,滾動並不像我想要的那麼順利。 我想優化創建PDF頁面的拇指圖像。 我想在CGContextDrawPDFPage之後創建一個CGContextRef並重置它的內容,因此我不必每次創建一個上下文並執行一些其他計算,這需要大量資源。使用CGContextDrawPDFPage繪製PDF頁面後重新設置CGContextRef
重置CGContextDrawPDFPage後的CGContextRef內容是否可能? CGContextRestoreGState和CGContextSaveGState在這種情況下似乎沒有幫助。
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GCPdfSource *pdfSource = [GCPdfSource sharedInstance];
for (int i = pageRange.location; i <= pageRange.length; i++) {
UIView *thumbPdfView = [scrollView viewWithTag:i+1];
if (thumbPdfView == nil) {
CGPDFPageRef pdfPage = [pdfSource pageAt:i + 1];
float xPosition = THUMB_H_PADDING + THUMB_H_PADDING * i + THUMB_WIDTH * i;
CGRect frame = CGRectMake(xPosition, THUMB_H_PADDING, THUMB_WIDTH, THUMB_HEIGHT);
thumbPdfView = [[UIView alloc] initWithFrame:frame];
thumbPdfView.opaque = YES;
thumbPdfView.backgroundColor = [UIColor whiteColor];
[thumbPdfView setTag:i+1];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
frame.size.width,
frame.size.height,
8, /* bits per component*/
frame.size.width * 4, /* bytes per row */
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextClipToRect(context, CGRectMake(0, 0, frame.size.width,frame.size.height));
CGRect pdfPageRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
CGRect contextRect = CGContextGetClipBoundingBox(context);
CGAffineTransform transform = aspectFit(pdfPageRect, contextRect);
CGContextConcatCTM(context, transform);
CGContextDrawPDFPage(context, pdfPage);
CGImageRef image = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *uiImage = [[UIImage alloc]initWithCGImage:image];
CGImageRelease(image);
UIImageView *imageVIew = [[UIImageView alloc]initWithImage:uiImage];
[uiImage release];
[thumbPdfView addSubview:imageVIew];
[imageVIew release];
[scrollView addSubview:thumbPdfView];
[thumbPdfView release];
}
}
[pool release];//release
和aspectFit功能...
CGAffineTransform aspectFit(CGRect innerRect, CGRect outerRect) {
CGFloat scaleFactor = MIN(outerRect.size.width/innerRect.size.width, outerRect.size.height/innerRect.size.height);
CGAffineTransform scale = CGAffineTransformMakeScale(scaleFactor, scaleFactor);
CGRect scaledInnerRect = CGRectApplyAffineTransform(innerRect, scale);
CGAffineTransform translation =
CGAffineTransformMakeTranslation((outerRect.size.width - scaledInnerRect.size.width)/2 - scaledInnerRect.origin.x,
(outerRect.size.height - scaledInnerRect.size.height)/2 - scaledInnerRect.origin.y);
return CGAffineTransformConcat(scale, translation);
}
謝謝!它的工作原理,現在我不需要每次繪製pdf頁面時創建一個上下文:) CGContextClearRect(context,CGContextGetClipBoundingBox(context)); 它並沒有像我期望的那樣有幫助(它在滾動速度太快時不太順利),但無論如何它比以前更好。 – Koteg 2010-07-09 12:27:02