使UIImage的一部分透明,或裁剪该区域

Wil*_*con 0 objective-c ios

我有这样的UIImage: 在此输入图像描述

我想在中间删除一个矩形,就像这样: 在此输入图像描述

Pau*_*l.s 10

打孔的最简单方法是添加图层蒙版.

  • #import <QuartzCore/QuartzCore.h>
  • 创建要剪辑的路径(要穿过的矩形)

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:yourView.bounds];
    [maskPath appendPath:[UIBezierPath bezierPathWithRect:rectToPunchThroughTheView]];
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后创建一个遮罩层并将其添加到视图中 - CAShapeLayer允许您定义任何路径

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.fillRule  = kCAFillRuleEvenOdd;
    maskLayer.fillColor = [UIColor blackColor].CGColor;
    maskLayer.path      = maskPath.CGPath;
    
    yourView.layer.mask = maskLayer;
    
    Run Code Online (Sandbox Code Playgroud)