线程安全UIImage调整大小?

时间:2012-04-25 15:52:25

标签: iphone multithreading uiimage resize scale

我做了这个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:进行缩放后立即保存到磁盘)。 / p>

我在后台线程中调用该方法。这可能是问题吗?我怎样才能将其重写为线程安全(假设问题是由线程引起的)。

1 个答案:

答案 0 :(得分: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();因为UIGraphicsGetCurrentContext();不是线程安全的。

希望,这会帮助你......享受