将大型CATiledLayer渲染到更小的区域

时间:2011-04-02 23:19:45

标签: objective-c render scaling catiledlayer

我有一个大小为4096 x 4096的CATiledLayer,我想渲染成一个尺寸为1024 x 1024的PNG

这不是这样做的......

-(NSData *)createPNGFormat
{
    UIGraphicsBeginImageContext(CGSizeMake(1024, 1024));
    tiledLayer.transform = CATransform3DMakeScale(0.25, 0.25, 1.0);
    [tiledLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(image);     

}

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

[First Hack]蛮力,按平铺渲染。这有效(慢慢地)

-(UIImage *)renderTileX:(NSInteger)xpos tileY:(NSInteger)ypos scale:(CGFloat)ascale
{
    CGSize tiledsize = tiledLayer.tileSize;
    CGRect tiledframe = tiledLayer.bounds;
    CALayer *container = [CALayer layer];
    container.frame = CGRectMake(0, 0, tiledsize.width,tiledsize.height);
    UIGraphicsBeginImageContext(tiledsize);
    [container addSublayer:tiledLayer];
    tiledLayer.frame = CGRectMake(-tiledsize.width*xpos,-tiledsize.height*ypos, tiledframe.size.width, tiledframe.size.height);
    [container renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [tiledLayer removeFromSuperlayer];

    CGFloat fsize = tiledsize.width*ascale;
    CGRect apicrect = CGRectMake(0,0,fsize,fsize);

    UIGraphicsBeginImageContext(apicrect.size);
    [image drawInRect:apicrect];
    UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return thumb;   


}


-(UIImage *)renderTiledLayer
{

    UIGraphicsBeginImageContext(CGSizeMake(1024, 1024));

    for (NSInteger x = 0 ; x<4; x++) {
        for (NSInteger y = 0; y < 4; y++) {
            NSLog(@"render %d:%d",x,y);
            UIImage *tile = [self renderTileX:x tileY:y scale:0.25];
            [tile drawAtPoint:CGPointMake(x*256, y*256)];
        }
    }
    UIImage *fimage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();


    return fimage;      
}

[使用Google ...]更好的方法

-(UIImage *)createThumb
{

    UIGraphicsBeginImageContext(CGSizeMake(1024, 1024));
    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 0.25, 0.25);
    [tiledLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *fimage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return fimage;  
}