2014-04-02 104 views
0

我有一個繪製圖像的類。它被多次實例化,用於多個圖像源,並且可能同時具有多個這些對象;每個獲取中斷驅動的源(來自USB設備)。核心圖形:如何同時繪製多個實例?

該類的一部分功能是註釋輸入的圖像,所以有一個例程會執行一些標準的Core Graphics來添加註釋。

我通過位圖上下文來做到這一點,我首先繪製圖像,然後使用標準CGContext的東西添加註釋。

問題是,當我這樣做時,來自多個來源的圖像彼此之間步調一致。它看起來像一個確定的背景;即使位圖上下文不是線程安全的。但是,我添加了NSLock,但這並沒有解決問題,所以它可能不僅僅是線程安全問題。

這裏是程序的大大簡化版本:

- (CGImageRef)createCopiedImage:(CGImageRef)inImage 
{ 
    CGImageRef ret = nil; 

    CGRect imageRect = CGRectMake (0, 0, CGImageGetWidth (ret), CGImageGetHeight (ret)); 
    size_t rowBytes = imageRect.size.width * 4; 
    size_t bufferLen = rowBytes * imageRect.size.height; 
    void *buffer = malloc (bufferLen); 

    if (buffer) 
    { 
     CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName (kCGColorSpaceGenericRGB); 

     if (colorSpace) 
     { 
     CGContextRef drawingContext = CGBitmapContextCreate (buffer, imageRect.size.width, imageRect.size.height, 8, rowBytes, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst); 

     if (drawingContext) 
     { 
      CGContextDrawImage (drawingContext, imageRect, inImage); 

      CFRelease (backGroundImage); 


      // DO ANNOTATION STUFF HERE 

      CGDataProviderRef dataProvider = CGDataProviderCreateWithData (NULL, buffer, rowBytes * imageRect.size.height, NULL); 

      if (dataProvider) 
      { 
       CGImageRef ret = CGImageCreate (imageRect.size.width, imageRect.size.height, 8, 32, rowBytes, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst, dataProvider, NULL, false, kCGRenderingIntentDefault); 

       CGDataProviderRelease (dataProvider) ; 
      } 

      CGContextRelease (drawingContext); 
     } 

    free (buffer); 
    } 

    return ret; 
} 

我如何才能避免這些情況下踩着對方的任何想法?

回答

1

沒有頂住內存泄露,你應該能夠讓系統內存分配給你,只是使用新創建繪圖複製出來的CGImageRef:

@implementation YourClass 

- (CGImageRef)createCopiedImage:(CGImageRef)inImage 
{ 
    CGImageRef ret = NULL; 

    CGRect imageRect = CGRectMake (0, 0, CGImageGetWidth (ret), CGImageGetHeight (ret)); 
    size_t rowBytes = imageRect.size.width * 4; 
    size_t bufferLen = rowBytes * imageRect.size.height; 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName (kCGColorSpaceGenericRGB); 

    if (colorSpace) 
    { 
     CGContextRef drawingContext = CGBitmapContextCreate (NULL, imageRect.size.width, imageRect.size.height, 8, rowBytes, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst); 

     if (drawingContext) 
     { 
      CGContextDrawImage (drawingContext, imageRect, inImage); 

      CFRelease (backGroundImage); 

      // DO ANNOTATION STUFF HERE 

      // Copy image out 
      ret = CGBitmapContextCreateImage(drawingContext); 

      CGContextRelease (drawingContext); 
     } 
    } 

    return ret; 
} 

@end