Why won't my CATiledLayer scroll in a UIScrollView after zooming?

落爺英雄遲暮 提交于 2019-12-06 22:46:25

Here's my first pass at fixing the obvious bugs:

#import <QuartzCore/QuartzCore.h>
#import "PracticeViewController.h"

@implementation PracticeViewController
@synthesize image;

- (void)viewDidLoad
{
    [super viewDidLoad];

    // You do not need to and must not autorelease [NSBundle mainBundle]
    NSString *path = [[NSBundle mainBundle] pathForResource:@"H-5" ofType:@"jpg"]; 
    NSData *data = [NSData dataWithContentsOfFile:path];
    image = [UIImage imageWithData:data];

    CGRect pageRect = CGRectMake(0,  0,  1600, 2400);

    CATiledLayer *tiledLayer = [CATiledLayer layer];
    tiledLayer.delegate = self;
    tiledLayer.tileSize = CGSizeMake(1024.0, 1024.0);
    tiledLayer.levelsOfDetail = 5; // was 1000, which makes no sense. Each level of detail is a power of 2.
    tiledLayer.levelsOfDetailBias = 0; // was 1000, which also makes no sense. 
    // Do not change the tiledLayer.frame.
    tiledLayer.bounds = pageRect; // I think you meant bounds instead of frame.
    // Flip the image vertically.
    tiledLayer.transform = CATransform3DMakeScale(zoom, -zoom, 1.0f);

    myContentView = [[UIView alloc] initWithFrame:self.view.bounds];
    [myContentView.layer addSublayer:tiledLayer];

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.delegate = self;
    scrollView.contentSize = pageRect.size;
    scrollView.maximumZoomScale = 32; // = 2 ^ 5
    [scrollView addSubview:myContentView];

    [self.view addSubview:scrollView];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return myContentView;
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"H-5" ofType:@"jpg"]; 
    NSData *data = [NSData dataWithContentsOfFile:path];
    image = [UIImage imageWithData:data];
    CGRect imageRect = CGRectMake (0.0, 0.0, image.size.width, image.size.height);
    CGContextDrawImage (context, imageRect, [image CGImage]);
}

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