- (NSImage *)updateImageFromImage:(CGImageRef)imgRef
withTransition:(CGFloat)transition
blur:(CGFloat)blur
{
CGFloat w = CGImageGetWidth(imgRef);
CGFloat h = CGImageGetHeight(imgRef);
CGRect grect = CGRectMake(0, 0, w, h);
CIImage *inputimg = [CIImage imageWithCGImage:imgRef];
// 创建模糊图 CIGaussianBlur
CIImage *blurimg = [[CIFilter filterWithName:@"CIGaussianBlur" keysAndValues:kCIInputImageKey, inputimg,
kCIInputRadiusKey,[NSNumber numberWithFloat:blur], nil] valueForKey:kCIOutputImageKey];
// 模糊图片的尺寸变大,需要进行裁剪
blurimg = [blurimg imageByCroppingToRect:grect];
// 创建两个线性渐变
CIImage *gradientimg1 = [[CIFilter filterWithName:@"CILinearGradient" keysAndValues:@"inputPoint0", [CIVector vectorWithX:0 Y:(1.0-transition)*h],
@"inputPoint1", [CIVector vectorWithX:0 Y:0.5*h],
@"inputColor0", [CIColor colorWithRed:0 green:1 blue:0 alpha:1],
@"inputColor1",[CIColor colorWithRed:0 green:1 blue:0 alpha:0], nil] valueForKey:kCIOutputImageKey];
// 执行裁剪操作后才能获取到渐变图片
gradientimg1 = [gradientimg1 imageByCroppingToRect:grect];
CIImage *gradientimg2 = [[CIFilter filterWithName:@"CILinearGradient" keysAndValues:@"inputPoint0", [CIVector vectorWithX:0 Y:transition*h],
@"inputPoint1", [CIVector vectorWithX:0 Y:0.5*h],
@"inputColor0", [CIColor colorWithRed:0 green:1 blue:0 alpha:1],
@"inputColor1",[CIColor colorWithRed:0 green:1 blue:0 alpha:0], nil] valueForKey:kCIOutputImageKey];
gradientimg2 = [gradientimg2 imageByCroppingToRect:grect];
// 由两个渐变创建Mask
CIImage * maskimg = [[CIFilter filterWithName:@"CIAdditionCompositing" keysAndValues:@"inputImage", gradientimg1,
@"inputBackgroundImage", gradientimg2, nil] valueForKey:kCIOutputImageKey];
// 合成聚焦图片
CIImage *combineimg = [[CIFilter filterWithName:@"CIBlendWithMask" keysAndValues:@"inputImage", blurimg,
@"inputBackgroundImage", inputimg,
@"inputMaskImage",maskimg, nil] valueForKey:kCIOutputImageKey];
NSCIImageRep *rep = [NSCIImageRep imageRepWithCIImage:combineimg];
NSImage *nsImage = [[NSImage alloc] initWithSize:rep.size];
[nsImage addRepresentation:rep];
return nsImage;
}