以下のコードを使用して、PDF ページのプレビューをレンダリングしています。ただし、大量のメモリ (ページあたり 2 ~ 3MB) を使用しています。
デバイスのログに次のように表示されます。
<Error>: CGBitmapContextInfoCreate: unable to allocate 2851360 bytes for bitmap data
ビットマップをカラー チャネルあたり 8 ビットでレンダリングする必要はありません。コードを変更して、グレースケールまたはチャネルあたりのビット数を減らすにはどうすればよいですか?
ビットマップが x/y の最大解像度でレンダリングされ、結果の画像が要求されたサイズにズームされるソリューションでも問題ありません。PDF は後で aCATiledLayer
とにかく詳細にレンダリングされます。
また、Apple のドキュメントによると、CGBitmapContextCreate()
(メモリが原因で) コンテキストを作成できない場合は NIL を返します。しかし、MonoTouch ではコンテキストを作成するコンストラクタしかないため、作成が失敗したかどうかを確認できません。できれば、ふりをしている画像をスキップできます。
UIImage oBackgroundImage= null;
using(CGColorSpace oColorSpace = CGColorSpace.CreateDeviceRGB())
// This is the line that is causing the issue.
using(CGBitmapContext oContext = new CGBitmapContext(null, iWidth, iHeight, 8, iWidth * 4, oColorSpace, CGImageAlphaInfo.PremultipliedFirst))
{
// Fill background white.
oContext.SetFillColor(1f, 1f, 1f, 1f);
oContext.FillRect(oTargetRect);
// Calculate the rectangle to fit the page into.
RectangleF oCaptureRect = new RectangleF(0, 0, oTargetRect.Size.Width / fScaleToApply, oTargetRect.Size.Height / fScaleToApply);
// GetDrawingTransform() doesn't scale up, that's why why let it calculate the transformation for a smaller area
// if the current page is smaller than the area we have available (fScaleToApply > 1). Afterwards we scale up again.
CGAffineTransform oDrawingTransform = oPdfPage.GetDrawingTransform(CGPDFBox.Media, oCaptureRect, 0, true);
// Now scale context up to final size.
oContext.ScaleCTM(fScaleToApply, fScaleToApply);
// Concat the PDF transformation.
oContext.ConcatCTM(oDrawingTransform);
// Draw the page.
oContext.InterpolationQuality = CGInterpolationQuality.Medium;
oContext.SetRenderingIntent (CGColorRenderingIntent.Default);
oContext.DrawPDFPage(oPdfPage);
// Capture an image.
using(CGImage oImage = oContext.ToImage())
{
oBackgroundImage = UIImage.FromImage( oImage );
}
}