标签:
关于高斯模糊的方式有很多种,但是如果需要模糊渐变,那么对这种高斯模糊算法的性能要求是比较高的,今天这里重点不讨论算法,只是提供一个动画实现的思路。动画效果如下:
高斯模糊渐变动画
//高斯模糊
-(UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
if (blur < 0.f || blur > 1.f) {
blur = 0.5f;
}
int boxSize = (int)(blur * 250);
boxSize = boxSize - (boxSize % 2) + 1;
CGImageRef img = image.CGImage;
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
void *pixelBuffer; //从CGImage中获取数据
CGDataProviderRef inProvider = CGImageGetDataProvider(img); CFDataRef inBitmapData = CGDataProviderCopyData(inProvider); //设置从CGImage获取对象的属性
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
if(pixelBuffer == NULL)
NSLog(@"No pixelbuffer");
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend); if (error) { NSLog(@"error from convolution %ld", error);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef ctx = CGBitmapContextCreate( outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast); CGImageRef imageRef = CGBitmapContextCreateImage (ctx); UIImage *returnImage = [UIImage imageWithCGImage:imageRef]; //clean up CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
CFRelease(inBitmapData);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageRef);
return returnImage;
}
自动渐变的过程需要加入一个定时器NSTimer
,并且循环。每0.1秒循环一次,通过一个变量来计数,以改变blur值。当然,这里的参数根据需要来调整来满足不同的需求。
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeImageView1) userInfo:nil repeats:YES];
-(void)changeImageView1 {
self.imageView1.image = [self boxblurImage:[UIImage imageNamed:@"login_bg_1"] withBlurNumber:self.count1/50.0];
if (self.count1++ == 15) {
[self.timer1 invalidate];
self.timer1 = nil;
self.count1 = 0;
self.imageView2.image = [UIImage imageNamed:@"login_bg_2"];
[UIView animateWithDuration:2 animations:^{
self.imageView1.alpha = 0;
self.imageView2.alpha = 1;
} completion:^(BOOL finished) {
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(imageView2AnimationStart) userInfo:nil repeats:NO];
}]; }
}
在第一张图片模糊到一定程度时,对其做渐变处理,改变其alpha
值(从1到0),同时让第二张图显现出来(从1到0)。至此,整个动画就基本完成了。
需要对其他方面做些优化,比如NSTimer
的开启与暂停,以及切换到其他页面后需要关闭定时器等。
标签:
原文地址:http://www.cnblogs.com/isItOk/p/5838308.html