iOS开发经验之动画失效

开发过程中遇到的一些小问题。

这两天做滤镜的代码,总是会概率性出现全局动画失效的情况。stackOverFlow 和 cocoaChina搜索了一下,得出结论可能是非主线程调用UI所致。仔细检查了一遍代码,并没有在非主线程调用UI,注释加断点,最后发现是在非主线程对image设置了滤镜所致。代码如下:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);

dispatch_queue_t syncqueue = dispatch_queue_create("com.snapsliderfilters.app",nil);

dispatch_apply(filters.count, queue, ^(size_t index){

SNFilter *filterComputed = [originalImage applyFilter:filters[index]];

dispatch_sync(syncqueue, ^{

[finalFilters addObject:filterComputed];

return;

});});


- (SNFilter*)applyFilter:(NSString*)filterName

{

SNFilter*filter = [selfcopy];

filter.name= filterName;

if(![self.filterNameListcontainsObject:filterName]) {

NSLog(@"这个滤镜不存在");

returnfilter;

}elseif([filterNameisEqualToString:@"No Filter"]) {

returnfilter;

}else{

CIImage*sourceImage = [[CIImagealloc]initWithCGImage:filter.image.CGImageoptions:nil];

CIFilter*myFilter = [CIFilterfilterWithName:filterName];

[myFiltersetDefaults];

[myFiltersetValue:sourceImageforKey:kCIInputImageKey];

CIContext*context = [CIContextcontextWithOptions:nil];

CGImageRefoutputCGImage = [contextcreateCGImage:myFilter.outputImagefromRect:myFilter.outputImage.extent];

UIImage* filteredImage = [UIImageimageWithCGImage:outputCGImage];

filter.image= filteredImage;

returnfilter;

}

returnnil;

}

其实这些ui并没有显示在屏幕上。因此渲染UI一定要在主线程不止是指显示在屏幕上的,也指ui的离屏处理。(会不会是线程安全问题?线程不安全最多造成数据错乱,而不应该是动画失效。也不很确定,对苹果底层动画渲染机制了解的不够多。)

处理方法:简单粗暴,直接for

for(inti =0; i < filters.count; i++) {

SNFilter*filterComputed = [originalImageapplyFilter:filters[i]];

[finalFiltersaddObject:filterComputed];

}

你可能感兴趣的:(iOS开发经验之动画失效)