0

我做了这个 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;
}

它在大多数情况下都有效,但在我最近的项目中,它输出原始图像(我在使用UIImageJPEGRepresentationimageWithData:缩放后立即保存到磁盘)。

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

4

1 回答 1

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(); 不是安全的。

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

于 2012-04-25T16:53:03.050 回答