Core Text を使用してテキストを描画するために、このチュートリアルが続きました。ビューに Web イメージを追加したいと考えています。以下のコードを使用すると、ダウンロード時間を待つ以外はすべて正常に動作します。
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw((CTFrameRef)self.coreTextFrame, context);
for (NSArray *imageData in self.images) {
UIImage *image = [UIImage imageWithData:[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[imageData objectAtIndex:0]]]];
CGRect imageBounds = CGRectFromString([imageData objectAtIndex:1]);
CGContextDrawImage(context, imageBounds, image.CGImage);
}
}
しかし、このコードはメインスレッドをブロックし、コードを次のように置き換えると:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFrameDraw((CTFrameRef)self.coreTextFrame, context);
for (NSArray *imageData in self.images) {
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString: [imageData objectAtIndex:0]]];
__block UIImage *image = nil;
CGRect imageBounds = CGRectFromString([imageData objectAtIndex:1]);
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *downloadImage){
image = downloadImage;
CGContextDrawImage(context, imageBounds, image.CGImage);
}];
[operation start];
}
}
有線になると画像の位置がずれます。