在Monotouch应用程序中,以下代码将页面从PDF文档转换为UIImage。它可以工作,但它没有正确处理PDF文档。
public class KillerLeak
{
public static void RunOnce()
{
using (CGPDFDocument doc = CGPDFDocument.FromFile("DMSWorkbook.pdf"))
{
Console.WriteLine("Opened: pages={0}", doc.Pages);
UIImage img = GetThumbImage(doc, 1000, 1);
img.Dispose();
}
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
}
private static UIImage GetThumbImage(CGPDFDocument document, float thumbContentSize, int pageNumber)
{
if ((pageNumber <= 0) || (pageNumber > document.Pages)) {
return null;
}
// Calc page view size
SizeF pageSize = new SizeF(768, 1024);
if (pageSize.Width % 2 > 0) {
pageSize.Width--;
}
if (pageSize.Height % 2 > 0) {
pageSize.Height--;
}
// Calc target size
var targetSize = new Size((int)pageSize.Width, (int)pageSize.Height);
// Draw page on CGImage
CGImage pageImage;
using (CGColorSpace rgb = CGColorSpace.CreateDeviceRGB()) {
using (CGBitmapContext context = new CGBitmapContext(null, targetSize.Width, targetSize.Height, 8, 0, rgb, CGBitmapFlags.ByteOrder32Little | CGBitmapFlags.NoneSkipFirst)) {
using (CGPDFPage pdfPage = document.GetPage(pageNumber)) {
RectangleF thumbRect = new RectangleF(0.0f, 0.0f, targetSize.Width, targetSize.Height);
context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
context.FillRect(thumbRect);
context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, thumbRect, 0, true));
context.SetRenderingIntent(CGColorRenderingIntent.Default);
context.InterpolationQuality = CGInterpolationQuality.Default;
context.DrawPDFPage(pdfPage);
pageImage = context.ToImage();
}
}
}
UIImage result = UIImage.FromImage(pageImage);
pageImage.Dispose();
return result;
}
}
如果我注释掉DrawPDFPage(...)行,代码不会泄漏。这是一个Monotouch错误还是我做错了什么?
答案 0 :(得分:1)
事实证明,泄漏与Monotouch无关,正如我之前所想。漏洞不会在IOS 5上发生,但在下一版仍处于测试版的IOS下会泄漏。我已经使用Monotouch和Objective-C编写的相同代码进行了测试,它们都表现出相同的行为。