iOS 不规则(多边形)图形,贝塞尔曲线绘制自定义图形

我们先来看看效果 :
未命名.gif

一、关于贝塞尔曲线UIBezierPath :

关于贝塞尔曲线的 : 基本概念和使用方法 .

二、使用:

1.创建贝塞尔曲线路径path对象.
UIBezierPath *path = [UIBezierPath bezierPath];
2.设置绘制图形的路径起点.
CGPoint point = CGPointMake(<#CGFloat x#>, <#CGFloat y#>);
[path moveToPoint:point];
3.设置绘制图形的路径的其他点(简单理解为转折点、转向点).
CGPoint point = CGPointMake(<#CGFloat x#>, <#CGFloat y#>);
[path addLineToPoint:point];
三、举例子:以左上角梯形为例 ↓
// 1、创建按钮
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(20, 100, 120, 50);
btn.backgroundColor = [UIColor orangeColor];
[btn setTitle:@"按钮" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
// 2、设置贝塞尔曲线路径

/* 所用宏: 
#define kViewWidth(View) CGRectGetWidth(View.frame)
#define kViewHeight(View) CGRectGetHeight(View.frame)
 */

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:CGPointMake(0.f, 0.f)];
[path addLineToPoint:CGPointMake(kViewWidth(btn), 0.f)];
[path addLineToPoint:CGPointMake(kViewWidth(btn) *3/4, btn.frame.size.height)];
[path addLineToPoint:CGPointMake(0.f, kViewHeight(btn)];

[path closePath];

// 3、绘制图形时添加path遮罩
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    CAShapeLayer *shapLayer = [CAShapeLayer layer];
    shapLayer.path = self.path.CGPath;
    self.layer.mask = shapLayer;
}
至此绘制出一个梯形:
Simulator Screen Shot - iPhone 6 - 2018-04-24 at 15.39.13.png
但是,绿色箭头所指区域还是可以响应Button的点击手势.
E2A1C616-3428-498B-B7A3-46533B65471D.png
为了只让我们绘制出来的梯形触发手势,在这里我们需要增加一个点击区域的判断:
// 点击的覆盖方法,点击时判断点是否在path内,YES则响应,NO则不响应
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    BOOL res = [super pointInside:point withEvent:event];
    if (res)
    {
        if ([self.path containsPoint:point])
        {
            return YES;
        }
        return NO;
    }
    return NO;
}

完。

附上Demo地址~

你可能感兴趣的:(iOS 不规则(多边形)图形,贝塞尔曲线绘制自定义图形)