ios - 使用羽化边缘裁剪图像

标签 ios uiimage

我想用羽化圆圈裁剪图像。我用它来裁剪图像,但它只是裁剪成正方形。

 CGImageRef imref = CGImageCreateWithImageInRect([newImage CGImage], faceRect);
 newSubImage = [UIImage imageWithCGImage:imref];

我想要的是用羽毛边缘裁剪?我应该用什么来实现它?

最佳答案

此片段将创建带有羽化边缘的圆形切口

result

第一个 featherLocations 变量可能是您唯一需要调整的变量

- (UIImage *) featheredImageWithImage:(UIImage *) image
{
    //  Locations of where the feather starts and ends (0 -> 1)
    const CGFloat featherLocations[] = {0.9, 1};

    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //  Draw the original image
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

    //  A 'knock-out' gradient is used to generate a feather effect,
    //  the alpha channel on the colors defines the alpha of the drawn image
    NSArray *gradientColors = @[(id)[UIColor colorWithWhite:0 alpha:1].CGColor,
                                (id)[UIColor colorWithWhite:0 alpha:0].CGColor];

    CGGradientRef gradient = CGGradientCreateWithColors(CGImageGetColorSpace(image.CGImage), (__bridge CFArrayRef)gradientColors, featherLocations);

    //  Because we're changing the draw mode below,
    //  take a snapshot of the current draw settings so we can reset them after
    CGContextSaveGState(ctx);

    //  The kCGBlendModeDestinationIn blend mode will provide a'knock-out' effect on
    //  the previously drawn content, using the alpha channels of the gradient's colors
    CGContextSetBlendMode(ctx, kCGBlendModeDestinationIn);

    const CGPoint gradientCenter = CGPointMake(image.size.width / 2, image.size.height / 2);

    //  The gradient will start at the center (0) and extend to the closest edge (horizontal or vertical)
    const CGFloat startRadius = 0;
    const CGFloat endRadius = MIN(image.size.width,
                                  image.size.height) / 2;

    //  Draw the gradient to eliminate the pixels we don't want
    CGContextDrawRadialGradient(ctx, gradient, gradientCenter, startRadius, gradientCenter, endRadius, (kCGGradientDrawsAfterEndLocation));

    CGGradientRelease(gradient);
    gradient = NULL;

    //  Finally, restore state
    //  (note that in this example CGContextSaveGState and CGContextRestoreGState
    //  are optional because no further drawing happens after this point)
    CGContextRestoreGState(ctx);

    //  Get the UIImage version
    UIImage *featheredImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return featheredImage;
}

关于ios - 使用羽化边缘裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158803/

相关文章:

ios - 更新 Collection View 项目

iphone - iOS - 用按钮反转 UIImage

ios - 如何在键盘上方添加工具栏?

ios - 如何使用ssziparchive解压缩包含多个文件夹的zip文件?

ios - xcode 6 ota 分发失败

ios - 对 UIImage 执行 floodfill

ios - 在 UIGraphicsBeginImageContext 中绘制时 UIImage 方向发生变化

ios - 在 iOS 中将字符串拆分为子字符串

ios - 在标签栏中的彩色 UIImage 周围绘制某种颜色的边框

swift - 从dae文件中获取预览图,显示在UIImage中