TiledView.h
@interface TiledView
- (id)initWithX:(int)tileXNum Y:(int)tileYNum;
@property (nonatomic) BOOL annotates;
@end
TiledView.m
#define TILE_SIZE 256
@implementation TiledView
- (id)initWithX:(int)tileXNum Y:(int)tileYNum
{
self = [super init];
if (self) {
CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
tiledLayer.contents = nil;
tiledLayer.levelsOfDetail = 1;
tiledLayer.levelsOfDetailBias = 0;
// logic for retina
float screenScale = [UIScreen mainScreen].scale;
tiledLayer.tileSize = CGSizeMake(TILE_SIZE*screenScale, TILE_SIZE*screenScale);
// bound is auto fit with retina
self.bounds = CGRectMake(0, 0, TILE_SIZE*tileXNum, TILE_SIZE*tileYNum);
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
// for UIView implemente
// real logic is implements on below
// - (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
}
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context {
CGRect rect = CGContextGetClipBoundingBox(context);
CGFloat scale = CGContextGetCTM(context).a;
CATiledLayer *tiledLayer = (CATiledLayer *)layer;
CGSize tileSize = tiledLayer.tileSize;
tileSize.width /= scale;
tileSize.height /= scale;
int col = floorf(CGRectGetMinX(rect) / tileSize.width);
int row = floorf(CGRectGetMinY(rect) / tileSize.height);
CGImageRef image = [self tileForScale:scale row:row col:col];
CGContextScaleCTM(context, 1, -1);
rect = CGContextGetClipBoundingBox(context);
if(NULL != image) {
CGContextDrawImage(context, rect, image);
CGImageRelease(image);
}
// draw line for debug
if (self.annotates) {
CGContextSetRGBStrokeColor(context, 0, 1, 0, 1);
CGContextSetLineWidth(context, 6.0 / scale);
CGContextStrokeRect(context, rect);
}
}
- (CGImageRef)tileForScale:(CGFloat)scale row:(int)y col:(int)x
{
NSString *path;
{
// path for tile
path = xxxx/x/y;
}
CGDataProviderRef provider;
if(path != nil) {
NSURL *imageURL = [NSURL fileURLWithPath:path];
provider = CGDataProviderCreateWithURL((CFURLRef)imageURL);
}
CGImageRef image = nil;
if(provider != nil) {
image = CGImageCreateWithJPEGDataProvider(provider, NULL, FALSE, kCGRenderingIntentDefault);
CFRelease(provider);
}
return image;
}
@end