CATiledLayer、CGContextDrawImage 和 CGContextTranslateCTM

JWo*_*ood 1 iphone objective-c quartz-graphics quartz-2d

我有一个大的UIScrollView,其中包含一个CATiledLayer我用来绘制更大的图块,drawRect:如下所示:

- (void)drawRect:(CGRect)rect {
    int firstCol = floorf(CGRectGetMinX(rect) / tileSize);
    int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize);
    int firstRow = floorf(CGRectGetMinY(rect) / tileSize);
    int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, tileSize);
CGContextScaleCTM(context, 1.0, -1.0);

    for( int row = firstRow; row <= lastRow; row++ ) {
    for( int col = firstCol; col <= lastCol; col++ ) {
            UIImage = [self getTileWithRow:row column:col];

            CGRect tileRect = CGRectMake((col * tileSize), 
                                         row * tileSize),
                                         tileSize, tileSize);

            CGContextTranslateCTM(context, 0, tileRect.size.height);
            CGContextScaleCTM(context, 1.0, -1.0);
            CGContextDrawImage(context, tileRect, tile.CGImage);
        }
    }

    CGContextRestoreGState(context);
}
Run Code Online (Sandbox Code Playgroud)

当我注释掉这工作CGContextSaveGStateCGContextSaveGStateCGContextScaleCTMCGContextRestoreGState电话,但图像是上下颠倒。调用就位后,根本不会绘制图像。我可以使用 [tile drawInRect:] 但这会反向绘制行,从而弄乱了更大的图像。

我在翻译上做错了什么?

编辑:按照建议将保存/恢复和转换移出循环,但它仍然没有绘制任何东西。

fis*_*ear 5

设置正确的转换以垂直翻转内容是出了名的困难。看不到任何东西的可能原因是因为转换将图像移到了矩形之外。我以前让它工作过,但不记得我是怎么做到的。现在我在 CATiledLayer 上设置了“geometryFlipped = YES”,它为我执行翻转。

顺便说一句,为什么不将 CATiledLayer 的“tileSize”设置为瓷砖的大小,那么你就不需要这个 for-loop 瓷砖映射的东西了。drawRect 为您的每个图块调用一次,因此您可以简单地执行以下操作:

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    int col = floorf(CGRectGetMinX(rect) / tileSize);
    int row = floorf(CGRectGetMinY(rect) / tileSize);

    UIImage tile = [self getTileWithRow:row column:col];

    CGContextDrawImage(context, rect, tile.CGImage);
}
Run Code Online (Sandbox Code Playgroud)