objective C如何从矩形视图中裁剪出三角形视图?

How to clip a triangular view from a rectangular view in objective C?

我想要如下图所示的视图:- desired view 我正在使用 UIBezierPath 和 CAShapeLayer 来存档以下代码:-

     UIBezierPath *path = [[UIBezierPath alloc] init];
//    [[UIColor blackColor] setStroke];
//    [[UIColor redColor] setFill];
    [path moveToPoint:CGPointMake(_pendingView.frame.origin.x, _pendingView.frame.origin.y)];
    [path addLineToPoint:CGPointMake(_pendingView.frame.origin.x+15, _pendingView.frame.origin.y+15)];
    [path addLineToPoint:CGPointMake(_pendingView.frame.origin.x, _pendingView.frame.origin.y+30)];
    [path closePath];

//    [path fill ]; 
//    [path stroke];
    CAShapeLayer *shapeLayer = [CAShapeLayer new];
    shapeLayer.frame = _pendingView.bounds;
    shapeLayer.path = path.CGPath;
    shapeLayer.fillColor = [UIColor redColor].CGColor;
    shapeLayer.strokeColor = [UIColor blackColor].CGColor;

    self.pendingView.layer.mask = shapeLayer;
   // [self.pendingView.layer addSublayer:shapeLayer];

但我无法实现。视图显示时没有裁剪和视图背景颜色。

P.S :- pendingview 是一个视图。

根据@inderJit 的建议,我纠正了我的代码,但我得到的是 output image 不是上面附加的那个。查看导致问题的背景颜色。我怎样才能做到这一点??

在您的代码中,您使用的是 _pendingView,即您的 UIView,绘图路径的原点,但图层将放置在 _pendingView 内,因此您无法获得正确的输出.

如需更多说明,您可以查看以下代码

UIBezierPath *path = [[UIBezierPath alloc] init];
//    [[UIColor blackColor] setStroke];
//    [[UIColor redColor] setFill];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(15, _vwArrow.frame.size.height/2)];
[path addLineToPoint:CGPointMake(0, _vwArrow.frame.size.height)];
[path closePath];

//    [path fill ];
//    [path stroke];
CAShapeLayer *shapeLayer = [CAShapeLayer new];
shapeLayer.frame = _vwArrow.bounds;
shapeLayer.path = path.CGPath;
shapeLayer.fillColor = self.view.backgroundColor.CGColor;
//    shapeLayer.strokeColor = [UIColor blackColor].CGColor;

//    _vwArrow.layer.masksToBounds = TRUE;
[_vwArrow.layer addSublayer:shapeLayer];
[self.view setNeedsDisplay];