这是我用来显示PGM格式图像的代码,它工作得更早,如果我将它作为一个单独的项目使用它但它现在不能正常工作,我也无法找到原因它不起作用。有人请帮助我。
- (void)viewDidLoad
{
[super viewDidLoad];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = self.view.center;
activityIndicator.frame= CGRectMake(center.x, center.y, 37, 37);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(center.x-30, center.y+40, 160, 30)];
[label setText:@"Calculating..."];
[self.view addSubview:activityIndicator];
[self.view addSubview:label];
[activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/////////////// read file ///////////
FILE *file = fopen("/Users/Sumit/Desktop/test/out.pgm", "rb");
if (file == NULL) {
NSLog(@"File Not Found");
return;
}
char name[20], secondline[10];
int w=0, h=0, colors=0;
fscanf(file, "%s", name);
fscanf(file, "%s", secondline);
fscanf(file, "%d %d %d", &w, &h, &colors);
//printf("%d %d\n", w, h);
unsigned char * imagedata = (unsigned char *) malloc(sizeof(unsigned char)*w*h);
fseek(file, 1, SEEK_CUR);
int i=0;
while (!feof(file)) {
int val = getc(file);
imagedata[i] = val;
i++;
}
fclose(file);
////////////////// end read file /////////////
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
CFDataRef rgbData = CFDataCreate(NULL, imagedata, w * h);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(rgbData);
CGImageRef rgbImageRef = CGImageCreate(w, h, 8, 8, w , colorspace, kCGBitmapByteOrderDefault, provider, NULL, true, kCGRenderingIntentDefault);
CFRelease(rgbData);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorspace);
UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
UIImage * newimage = [UIImage imageWithCGImage:rgbImageRef];
//imageview.frame = CGRectMake(imageview.frame.origin.x,imageview.frame.origin.y, w, h);
[imageview setImage:newimage];
[activityIndicator removeFromSuperview];
[label removeFromSuperview];
CGSize boundsSize = scrollview.bounds.size;
CGRect frameToCenter = imageview.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
imageview.frame = frameToCenter;
[scrollview addSubview:imageview];
CGImageRelease(rgbImageRef);
dispatch_async(dispatch_get_main_queue(), ^(void){
//[alertView dismissWithClickedButtonIndex:0 animated:YES];
});
});
// Do any additional setup after loading the view.
}
答案 0 :(得分:3)
您必须在主线程上修改每个UI。您在另一个线程上设置图像view.image。这是你的问题。
dispatch_async(dispatch_get_main_queue(), ^{
imageview.image = newimage;
});
您的实际代码会影响到,您的图像在[imageview setImage:newimage]之后不会立即设置; line,因为它在后台线程上。它将在稍后设定。