2012-04-25 71 views
0

我做這個的UIImage擴展得到重新調整副本:線程安全的UIImage調整大小?

-(UIImage*)scaleByRatio:(float) scaleRatio 
{ 
    CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); 

    //The output context. 
    UIGraphicsBeginImageContext(scaledSize); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

//Percent (101%)  
#define SCALE_OVER_A_BIT 1.01 

    //Scale. 
    CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT); 
    [self drawAtPoint:CGPointZero]; 

    //End? 
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return scaledImage; 
} 

它的工作原理在大多數情況下,但在我最近的項目是使用UIImageJPEGRepresentation縮放之後的原始圖像(我保存到磁盤輸出imageWithData:)。

我在後臺線程中調用該方法。這可能是問題嗎?我怎麼能重寫這是線程安全的(假設問題是由線程引起的)。

+2

我不認爲這個問題是後臺線程。但請記住,所有到用戶屏幕的繪圖都應在主線程中進行 – Lefteris 2012-04-25 16:19:53

+0

因此,如果此圖像顯示在UI中,並且調整大小(scaleByRatio函數)在後臺線程上調用,那會是一個問題嗎? – c0d3Junk13 2016-10-19 14:00:54

回答

2
-(UIImage*)scaleByRatio:(float) scaleRatio 
{ 
    CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); 
    CGColorSpaceRef colorSpace; 
    int bitmapBytesPerRow; 
    bitmapBytesPerRow = (size.width * 4); 

    //The output context. 
    UIGraphicsBeginImageContext(scaledSize); 
    CGContextRef context = context = CGBitmapContextCreate (NULL, 
           scaledSize .width, 
           scaledSize .height, 
           8,  // bits per component 
           bitmapBytesPerRow, 
           colorSpace, 
           kCGImageAlphaPremultipliedLast); 

//Percent (101%)  
#define SCALE_OVER_A_BIT 1.01 

    //Scale. 
    CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT); 
[self drawAtPoint:CGPointZero]; 

    //End? 
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return scaledImage; 
} 

在-總之你CGContextRef使用CGBitmapContextCreate不使用UIGraphicsGetCurrentContext()創建; becuase UIGraphicsGetCurrentContext();是不安全的。

希望,這將幫助你...享受

+0

當然有幫助,謝謝。 – Geri 2012-04-25 18:46:39

+0

在CGBitmapContextCreate中,我得到一個崩潰和一個警告,說函數調用參數是一個未初始化的值。 – c0d3Junk13 2016-10-19 14:10:35

相關問題