2013-07-12 78 views
3

我有一個CATiledLayer支持的UIScrollView,它顯示了一個非常大的圖像。 我想實現的是將此視圖捕獲到UIImage中(將其用作進度欄視圖的背景)。 有幾個問題:iOS - CATiledLayer renderInContext:結果扭曲的圖像

  • 在「100%」變焦(整個畫面可見的)它似乎確定
  • ,如果我在滾動視圖放大,一些瓷磚成爲扭曲(規模和/或偏移是壞的)
  • 試圖與蘋果公司的PhotoScroller樣品,幾乎工作,但拍攝的圖像有時被像素化
  • 我沒有寫代碼來攝製,所以我不知道如何解決它

經過對此其他計算器條目,但他們沒有太大的幫助...

圖像捕捉代碼:

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的代碼:方法:

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

任何想法?

回答

2

經過大量的反覆試驗,結果證明Cocoa實現本身並不完整,所以問題無法解決。

與iOS 7的釋放有雖然一種新的方法:

[view drawViewHierarchyInRect:rect afterScreenUpdates:YES]; 

(代替renderInContext),以及它的工作原理(圖像有些模糊,但是那一個可接受的副作用)。

+0

我無法對此表示感謝。在找到這篇文章之前,我幾個小時都在渲染不正確的快照。 –

+0

但這樣,圖像變形!它的形狀根本不合適。 @Asylum –