使用CoreGraphics CGContextDrawImage在CATiledLayer中绘制图像

6
我想在iPhone OS 3.1.3中使用CATiledLayer,为此,所有绘图都必须仅使用coregraphics在-(void)drawLayer:(CALayer *)layer inContext:(CGContext)context 中完成。
现在,我遇到了iPhone上翻转坐标系统的问题,并有一些建议如何使用变换来解决: 我的问题是我无法让它正常工作。我开始使用PhotoScroller示例代码,并用仅限于coregraphics调用的绘图方法替换了它。它看起来像这样:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
CGContextSaveGState(context);
CGRect rect = CGContextGetClipBoundingBox(context);
CGFloat scale = CGContextGetCTM(context).a;
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(0.f, rect.size.height));
CGContextConcatCTM(context, CGAffineTransformMakeScale(1.f, -1.f));

CATiledLayer *tiledLayer = (CATiledLayer *)layer;
CGSize tileSize = tiledLayer.tileSize;


tileSize.width /= scale;
tileSize.height /= scale;
// calculate the rows and columns of tiles that intersect the rect we have been asked to draw
int firstCol = floorf(CGRectGetMinX(rect) / tileSize.width);
int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
int firstRow = floorf(CGRectGetMinY(rect) / tileSize.height);
int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);
for (int row = firstRow; row <= lastRow; row++) {
    for (int col = firstCol; col <= lastCol; col++) {
     //   if (row == 0 ) continue;
        UIImage *tile = [self tileForScale:scale row:row col:col];
        CGImageRef tileRef = [tile CGImage];
        CGRect tileRect = CGRectMake(tileSize.width * col, tileSize.height * row,
                                     tileSize.width, tileSize.height);
        // if the tile would stick outside of our bounds, we need to truncate it so as to avoid
        // stretching out the partial tiles at the right and bottom edges
        tileRect = CGRectIntersection(self.bounds, tileRect);
        NSLog(@"row:%d, col:%d, x:%.0f y:%.0f, height:%.0f, width:%.0f", row, col,tileRect.origin.x, tileRect.origin.y, tileRect.size.height, tileRect.size.width);

        //[tile drawInRect:tileRect];
        CGContextDrawImage(context, tileRect, tileRef);
// just to draw the row and column index in the tile and mark the origin of the tile with a red line        
        if (self.annotates) {
            CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor]CGColor]);
            CGContextSetLineWidth(context, 6.0 / scale);
            CGContextStrokeRect(context, tileRect);
            CGContextSetStrokeColorWithColor(context, [[UIColor redColor]CGColor]);
            CGContextMoveToPoint(context, tileRect.origin.x, tileRect.origin.y);
            CGContextAddLineToPoint(context, tileRect.origin.x+100.f, tileRect.origin.y+100.f);
            CGContextStrokePath(context);
            CGContextSetStrokeColorWithColor(context, [[UIColor redColor]CGColor]);
            CGContextSetFillColorWithColor(context, [[UIColor whiteColor]CGColor]);
            CGContextSelectFont(context, "Courier", 128, kCGEncodingMacRoman);
            CGContextSetTextDrawingMode(context, kCGTextFill);
            CGContextSetShouldAntialias(context, true);
            char text[30]; 
            int length = sprintf(text,"row:%d col:%d",row,col);
            CGContextSaveGState(context);
            CGContextShowTextAtPoint(context, tileRect.origin.x+110.f,tileRect.origin.y+100.f, text, length);
            CGContextRestoreGState(context);
        }
    }
}

CGContextRestoreGState(context);

}

如您所见,我正在使用比例变换来反转坐标系,并使用平移变换将原点移动到左下角。图像绘制正确,但只绘制了第一行瓷砖。我认为平移操作或计算瓷砖坐标的方式存在问题。
这是它的外观:

我对所有这些转换有点困惑。

奖励问题: 如何在核心图形中处理视网膜显示图片?

编辑: 为了使其在视网膜显示器上正常工作,我只是采用了示例代码中提供图像的原始方法:

- (UIImage *)tileForScale:(CGFloat)scale row:(int)row col:(int)col
{
// we use "imageWithContentsOfFile:" instead of "imageNamed:" here because we don't want UIImage to cache our tiles
NSString *tileName = [NSString stringWithFormat:@"%@_%d_%d_%d", imageName, (int)(scale * 1000), col, row];
NSString *path = [[NSBundle mainBundle] pathForResource:tileName ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
}

原则上,由于核心图形库使用像素而不是点来工作,因此忽略显示的比例尺。因此,在要求绘制更多像素时,将使用更多的CATiledLayers(或子层)来填充屏幕。
感谢 Thomas
1个回答

10

Thomas,我一开始是按照WWDC 2010 ScrollView讲座的步骤进行的,但是在iOS 3.x中使用drawLayer:inContext时几乎没有文档可供参考。当我将演示代码从drawRect:移植到drawLayer:inContext:时,也遇到了与你相同的问题。

经过一些调查发现,在drawLayer:inContext:中,从CGContextGetClipBoundingBox(context)返回的rect的大小和偏移量正好是你想要绘制的内容。而drawRect:则给出了整个边界。

知道这一点后,您可以删除行列迭代以及边缘图块的CGRect交集,并在将上下文平移后仅绘制矩形。

以下是我的最终代码:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
  CGRect rect = CGContextGetClipBoundingBox(ctx);
  CGFloat scale = CGContextGetCTM(ctx).a;

  CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
  CGSize tileSize = tiledLayer.tileSize;
  tileSize.width /= scale;
  tileSize.height /= scale;

  int col = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
  int row = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);

  CGImageRef image = [self imageForScale:scale row:row col:col];

  if(NULL != image) {
    CGContextTranslateCTM(ctx, 0.0, rect.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    rect = CGContextGetClipBoundingBox(ctx);

    CGContextDrawImage(ctx, rect, image);
    CGImageRelease(image);
  }
}

需要注意的是TranslateCTMScaleCTM之后rect被重新定义了。

下面是我imageForScale:row:col函数的参考代码:

- (CGImageRef) imageForScale:(CGFloat)scale row:(int)row col:(int)col {
  CGImageRef image = NULL;
  CGDataProviderRef provider = NULL;
  NSString *filename = [NSString stringWithFormat:@"img_name_here%0.0f_%d_%d",ceilf(scale * 100),col,row];
  NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"png"];

  if(path != nil) {
    NSURL *imageURL = [NSURL fileURLWithPath:path];

    provider = CGDataProviderCreateWithURL((CFURLRef)imageURL);

    image = CGImageCreateWithPNGDataProvider(provider,NULL,FALSE,kCGRenderingIntentDefault); 
    CFRelease(provider);
  }
  return image;
}

这两个函数仍需要一些工作才能正确地支持高分辨率图形,但在除 iPhone 4 以外的所有设备上都看起来不错。


谢谢你的回答。难道不可以只使用[[UIImage imageNamed:@"imageName"] CGImage]方法来获取适用于Retina显示屏的正确图像吗?因为UIImage方法应该会获取正确的分辨率。 - GorillaPatch
非常好用!谢谢!我基本上使用了示例代码中的方法来提供图像瓦片,因此在Retina显示屏上,它只是以不同的缩放比例显示更多的瓦片以绘制图像。我已将该方法添加到原始问题中。 - GorillaPatch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接