使用CGContextDrawImage在块中图像位置错误

时间:2014-06-30 09:16:43

标签: ios core-text cgcontextdrawimage

我跟着this tutorial使用Core Text绘制文字,我想在视图中添加网页图片。 当我使用下面的代码时,一切正常,除了等待下载时间。

- (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);
    }
}

the correct effect

但是这段代码阻止了主线程,当我替换这样的代码时:

- (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];

    }
}

它变为有线,图像位置错误。 the wrong effect

0 个答案:

没有答案