【问题标题】:CGContextDrawPDFPage taking up large amounts of memoryCGContextDrawPDFPage 占用大量内存
【发布时间】:2011-02-27 20:22:12
【问题描述】:

我有一个 PDF 文件,我想以大纲形式绘制。我想在文档的前几页中分别绘制它们自己的 UIImage 以在按钮上使用,以便在单击时,主显示将导航到单击的页面。

但是,CGContextDrawPDFPage 在尝试绘制页面时似乎正在使用大量内存。尽管图像应该只有大约 100 像素高,但应用程序在特别是绘制一页时会崩溃,根据 Instruments 的说法,仅为一页分配大约 13 MB 的内存。

绘制代码如下:

//Note: This is always called in a background thread, but the autorelease pool is setup elsewhere
+ (void) drawPage:(CGPDFPageRef)m_page inRect:(CGRect)rect inContext:(CGContextRef) g { 
    CGPDFBox box = kCGPDFMediaBox;
    CGAffineTransform t = CGPDFPageGetDrawingTransform(m_page, box, rect, 0,YES);
    CGRect pageRect = CGPDFPageGetBoxRect(m_page, box);

    //Start the drawing
    CGContextSaveGState(g);

    //Clip to our bounding box
    CGContextClipToRect(g, pageRect);   

    //Now we have to flip the origin to top-left instead of bottom left
    //First: flip y-axix
    CGContextScaleCTM(g, 1, -1);
    //Second: move origin
    CGContextTranslateCTM(g, 0, -rect.size.height);

    //Now apply the transform to draw the page within the rect
    CGContextConcatCTM(g, t);

    //Finally, draw the page
    //The important bit.  Commenting out the following line "fixes" the crashing issue.
    CGContextDrawPDFPage(g, m_page);

    CGContextRestoreGState(g);
}

有没有更好的方法来绘制这个不占用大量内存的图像?

【问题讨论】:

  • 本帖结束后你是如何更新视图的?

标签: iphone cocoa-touch pdf core-graphics


【解决方案1】:

看看我在 github 上的 PDF 图像切片器代码:

http://github.com/luciuskwok/Maps-Slicer

设备上应该有足够的内存,13 MB 的分配不会杀死应用程序。每次渲染 PDF 时是否都在耗尽自动释放池?您可能还希望将渲染缓存到 UIImage 中,这样它就不必在每次显示时都渲染它。

【讨论】:

  • 好吧,问题不会通过 chaching 结果来解决,因为它在尝试绘制第一张图像时会崩溃。考虑到绘制图像并不是当时唯一发生的事情(它还使用 UIWebView 来显示完整的 PDF 文件),13 MB 可能太多了。
  • 嗨,Ed Marty,您有什么解决方案可以解决您的问题吗?我也面临同样的问题。如果您发现任何溶胶,请与我分享。谢谢
【解决方案2】:

尝试添加:

CGContextSetInterpolationQuality(g, kCGInterpolationHigh);
CGContextSetRenderingIntent(g, kCGRenderingIntentDefault); 

之前:

CGContextDrawPDFPage(g, m_page);

我遇到了类似的问题,添加上面的 2 个函数调用导致渲染使用的内存减少了 5 倍。可能是CGContextXXX绘图函数中的错误

【讨论】:

  • 显着减少内存和显着加快渲染时间(这比内存使用更让我感到沮丧)。 wtf,那些应该是默认值。谢天谢地,我遇到了你的答案,约翰——谢谢。
猜你喜欢
  • 2014-05-11
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多