Render large CATiledLayer into smaller area

余生颓废 提交于 2019-12-06 21:52:31

[First Hack] Brute Force , Render tile by tile. This works (slowly)

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

[Using the Google...] The better way

-(UIImage *)createThumb
{

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

    return fimage;  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!