Iphone 线程安全的图像大小调整?
我制作此UIImage扩展以获得重新缩放的副本:Iphone 线程安全的图像大小调整?,iphone,multithreading,uiimage,resize,scale,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); CGC
-(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:进行缩放后立即保存到磁盘)
我在后台线程中调用该方法。这可能是问题所在吗?如何将其重写为线程安全的(假设问题是由线程引起的)
简而言之,您必须使用CGBitmapContextCreate
创建CGContextRef
而不是使用UIGraphicsGetCurrentContext();因为使用UIGraphicsGetCurrentContext();萨尔不安全
希望,这将帮助您…享受我认为问题不在于背景线程。但是请记住,用户屏幕上的所有绘图都应该在主线程中进行,因此,如果此图像显示在UI中,并且在后台线程上调用了调整大小(scaleByRatio函数),这会有问题吗?在CGBitmapContextCreate中,我遇到一个崩溃,并警告说函数调用参数是未初始化的值。
-(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;
}