iOS 给 UIImageView “挖个洞”

最近在做的项目遇见的 UI 处理:
UI 效果图:
iOS 给 UIImageView “挖个洞”

首先分析一下怎么组合成这个效果:

  1. 最底部 背景图片
  2. 黑胶唱片图片
  3. 封面图片(后台给图片的 url)
  4. 光影遮罩图片

问题来了,怎么给 UIImageView 挖个半圆的洞,来显示下面的图层,显示部分黑胶唱片图片和背景图片?

代码:

- (void)overlayClipping:(UIImage *)image
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    // 半径
    CGFloat radius = image.size.height * (26.0 / 180.0);
    // 半圆
    [path addArcWithCenter:CGPointMake(image.size.width,image.size.height * 0.5) radius:radius startAngle:M_PI_2 endAngle:M_PI_2 * 3 clockwise:YES];
    
    UIGraphicsBeginImageContext(image.size);
    
    [path fill];
    [image drawAtPoint:CGPointZero];
    
    // Clip to the bezier path and clear that portion of the image.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddPath(context,path.CGPath);
    CGContextClip(context);
    CGContextClearRect(context,
                       CGRectMake(0,0,image.size.width,image.size.height)
                       );
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    image = newImage;
    self.coverImageView.image = image;
}

用法:

1.本地图片

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self overlayClipping:[UIImage imageNamed:@"yourImageName"]];
    }

2.网络图片
使用 sdwebimage 下载图片,拿到 image 对象

   [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:@"http://seopic.699pic.com/photo/50035/0520.jpg_wh1200.jpg"]
                           placeholderImage:[UIImage imageNamed:@"placeholderImage"]
                                  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                                      [self overlayClipping:image];
    }];

结合自己实际需求,可能不一定都是半圆, 修改 UIBezierPath 的 path 就可以。