Mac 上Tilt-Shift 效果的实现代码

- (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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值