我有一个CATiledLayer支持的UIScrollView,它显示了一个非常大的图像。 我想要实现的是将此视图捕获到UIImage中(将其用作进度条视图的背景)。 有几个问题:
检查了关于此的其他stackoverflow条目,但它们没有多大帮助......
图像捕获代码:
CGRect rect = [view bounds];
UIImage* img = nil;
if ([view isKindOfClass:[UIScrollView class]])
{
UIScrollView* scrollview = (UIScrollView*)view;
CGPoint contentOffset = scrollview.contentOffset;
UIGraphicsBeginImageContextWithOptions(rect.size, view.opaque, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, -contentOffset.x, -contentOffset.y);
[view.layer renderInContext:ctx];
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
平铺视图的代码是drawRect:method:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
if (self.clipContent)
{
CGContextSaveGState(context);
CGFloat color[4] = {1.0, 1.0f, 1.0f, 1.0f};
CGContextSetFillColor(context, color);
CGContextFillRect(context, self.bounds);
CGRect clips[] = {
CGRectMake(self.bounds.size.width / 2.0, 0,
self.bounds.size.height / 2.0 , self.bounds.size.width / 2.0)
};
CGContextClipToRects(context, clips, sizeof(clips) / sizeof(clips[0]));
}
CGFloat scale = CGContextGetCTM(context).a;
CGSize tileSize = [_dataSource tileSize];
double width = (double)tileSize.width / (double)scale;//pow(2.0, (int)log2(scale));
double height = (double)tileSize.height / (double)scale;//pow(2.0, (int)log2(scale));
int firstCol = floorf(CGRectGetMinX(rect) / width);
int lastCol = floorf((CGRectGetMaxX(rect) - 1) / width);
int firstRow = floorf(CGRectGetMinY(rect) / height);
int lastRow = floorf((CGRectGetMaxY(rect) - 1) / height);
for (int row = firstRow; row <= lastRow; row++) {
for (int col = firstCol; col <= lastCol; col++) {
UIImage* tileImage = [_dataSource tileForScale:scale row:row col:col];
CGRect tileRect = CGRectMake(width * col, height * row, width, height);
tileRect = CGRectIntersection(rect, tileRect);
[tileImage drawInRect:tileRect];
}
}
if (self.clipContent)
CGContextRestoreGState(context);
}
有什么想法吗?
答案 0 :(得分:2)
经过大量的反复试验,结果证明Cocoa实现本身不完整,所以问题无法解决。
随着iOS 7的发布,有一种新的方法:
[view drawViewHierarchyInRect:rect afterScreenUpdates:YES];
(而不是renderInContext),它可以工作(图像有些模糊,但这是可以接受的副作用)。