1

renderInContext に関する興味深いバグがあるようです。

私は、スクラップブックビュー内でテキスト、色付きの四角形、写真を自由に配置できる「スクラップブック」アプリに取り組んでいます。ユーザーは、組み込みの写真コレクション (imageNamed: を介してロード) からの写真と、アセット ライブラリからの写真の両方を追加できることに注意してください。

私のコードは、スクラップブック ビューとそのすべてのサブビューから、必要に応じて PDF とサムネイルの両方を作成します。最初に PDFContext (PDF の場合) または ImageContext (サムネイル画像の場合) を作成し、次に、scrapBookView.layer で renderInContext を呼び出します。

一般に、コードは機能しますが、1 つの例外について説明します。PDF を作成すると、組み込みの画像とアセット ライブラリの画像の両方がレンダリングされた PDF に正しく含まれます。ただし、サムネイルを作成すると、組み込みの画像は表示されますが、アセット ライブラリの画像が正しく表示されません。他の場所では背景色を明るい灰色に設定しましたが、画像自体が存在しないため、imageView が存在することはわかっています。

画像を画像ビューにロードするための非同期要素が存在する可能性があり、アセット ライブラリの画像が ImageContext にレンダリングされているときに、画像が十分な速度でそこに到達しない可能性があると思われます。

これは可能ですか?そうでない場合、renderInContext が PDFContext ではうまく機能するのに、ImageContext ではうまく機能しないのはなぜでしょうか?

さらに、アセット ライブラリの画像をサムネイルに含める方法を教えてください。

PDF 表現とサムネイルの両方が、scrapbookView のメソッドを介して作成されます。コードは次のとおりです。

PDF を作成するには:

-(NSData*) pdfRepresentation
{
     //== create a pdf context
     NSMutableData* result = [[NSMutableData alloc] init];
     UIGraphicsBeginPDFContextToData(result, self.bounds, nil);
     UIGraphicsBeginPDFPage();

     //== draw this view into it
     [self.layer renderInContext: UIGraphicsGetCurrentContext()];  // works for asset library images

     //== add a rectangular frame also
     CGContextRef pdf = UIGraphicsGetCurrentContext();
     CGContextAddRect(pdf, self.bounds);
     [[UIColor lightGrayColor] setStroke];
     CGContextStrokePath(pdf);

     //== clean up and return the results
     UIGraphicsEndPDFContext();
     return [result copy];
}

サムネイルを作成するには:

-(UIImage*) thumbnailRepresentation
{
     //== create a large bitmapped image context
     CGFloat minSpan = MIN(self.bounds.size.height, self.bounds.size.width);
     CGSize imageSize = CGSizeMake(minSpan, minSpan);
     UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0.0);

     //== draw the current view into the bitmap context
     self.backgroundColor = [UIColor whiteColor];
     [self.layer renderInContext: UIGraphicsGetCurrentContext()];  // doesn't work for asset library images
     self.backgroundColor = [UIColor clearColor];

     //== get the preliminary results
     UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();

     //== create a smaller image from this image
     CGFloat thumbnailWidth = 40.0;
     CGFloat scaleFactor = thumbnailWidth / minSpan;
     UIImage* result = [UIImage imageWithCGImage:[image CGImage] scale:scaleFactor orientation:UIImageOrientationUp];

     return result;
}
// btw - seems wasteful to create such a large intermediate image

どんな助けでも大歓迎です。

4

0 に答える 0