我在使用 CATiledLayer 时遇到了问题...我有一张大图像,一张地图,即 4726 x 2701。基本上我需要将此图像分解为图块并能够放大以查看很多细节,还能够一路放大,看到整个地图。使用我当前的实现,如果滚动视图的缩放级别设置为 1.0(最大缩放比例),它可以完美地工作,但是如果你缩小瓷砖被错误地替换。
这里缩放级别设置为 1.0。地图看起来很完美。
但是,如果缩放级别一直是(我相信是 0.2),那么地图就会一团糟。我应该看到整个地图,而不仅仅是两个图块。
这是我从大图像中获取图块的方法:
- (UIImage *)tileForScale:(CGFloat)scale row:(int)row col:(int)col {
float tileSize = 256.0f;
CGRect subRect = CGRectMake(col*tileSize, row * tileSize, tileSize, tileSize);
CGImageRef tiledImage = CGImageCreateWithImageInRect([mapImage CGImage], subRect);
UIImage *tileImage = [UIImage imageWithCGImage: tiledImage];
return tileImage;
}
我正在像 Apple 在 PhotoScroller 应用程序中一样显示图块。
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat scale = CGContextGetCTM(context).a;
CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
CGSize tileSize = tiledLayer.tileSize;
tileSize.width /= scale;
tileSize.height /= scale;
int firstCol = floorf(CGRectGetMinX(rect) / tileSize.width);
int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
int firstRow = floorf(CGRectGetMinY(rect) / tileSize.height);
int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);
for (int row = firstRow; row <= lastRow; row++) {
for (int col = firstCol; col <= lastCol; col++) {
UIImage *tile = [self tileForScale:scale row:row col:col];
CGRect tileRect = CGRectMake(tileSize.width * col, tileSize.height * row,
tileSize.width, tileSize.height);
tileRect = CGRectIntersection(self.bounds, tileRect);
[tile drawInRect:tileRect];
}
}
}
此外,这是我设置细节级别的代码,它为我的图像返回 4:
- (id)initWithImageName:(NSString *)name andImage:(UIImage*)image size:(CGSize)size {
self = [super initWithFrame:CGRectMake(0, 0, size.width, size.height)];
if (self) {
_imageName = [name retain];
mapImage = [image retain];
CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
tiledLayer.levelsOfDetail = [self zoomLevelsForSize:mapImage.size];
}
return self;
}
- (NSUInteger)zoomLevelsForSize:(CGSize)imageSize {
int zLevels = 1;
while(YES) {
imageSize.width /= 2.0f;
imageSize.height /= 2.0f;
if(imageSize.height < 256.0 || imageSize.width < 256.0) break;
++zLevels;
}
return zLevels;
}
我假设它与平铺大小和缩放比例有关,但我真的不知道如何解决这个问题。我似乎无法在 Google 上找到任何解决我的问题的方法。任何帮助都会很棒!:)