2012-04-25 14 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:)。

私はバックグラウンドスレッド内でメソッドを呼び出します。これが問題だろうか?これをスレッドセーフであるように書き直すにはどうすればよいですか(問題はスレッディングによって引き起こされると仮定します)。あなたがUIGraphicsGetCurrentContextを()を使用していないCGBitmapContextCreateを使用してCGContextRefを作成する必要がで短

+2

問題はバックグラウンドスレッドではないと思います。しかし、ユーザの画面への描画はすべてメインスレッド – Lefteris

+0

で行う必要があることに注意してください。このイメージがUIに表示され、バックグラウンドスレッドでサイズ変更(scaleByRatio関数)が呼び出されると問題になりますか? – c0d3Junk13

答えて

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

。 UIGraphicsGetCurrentContext();トライドルは安全ではありません。

希望すると楽しいですよ...

+0

もちろん、助けてくれてありがとう。 – Geri

+0

CGBitmapContextCreateでクラッシュし、関数呼び出しの引数が初期化されていないという警告が表示されます。 – c0d3Junk13

関連する問題