1

我跟着本教程使用 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];

    }
}

它变成有线的,图像的位置是错误的。 错误的效果

4

0 回答 0