在iOS开发中,我们经常会遇到让写一个聊天气泡或者不规则图形,常见的就是一个方框带一个三角,用来指向。
举个例子:现在我们又一个按钮,点击按钮之后弹出一个气泡框,要求弹出之后有一个三角形在弹框那里指向按钮。
我采用的是用点连线画一个,那么一个这样的视图需要几个点呢?如图1:
答案是7个
各个点如下
以左上角的红点为第一个点,顺时针旋转,总共7个点:
在画图之前我们需要已知下列条件:
1.视图的整体的frame;
2.三角的size以及三角顶点的point;
在控制器里面创建一个按钮和带有三角的视图,并调用绘制方法
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *signBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[signBtn setTitle:@"签名" forState:UIControlStateNormal];
[signBtn setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal];
signBtn.frame = CGRectMake(230, 100, 50, 20);
signBtn.layer.borderWidth = 1.0;
signBtn.layer.borderColor = [UIColor magentaColor].CGColor;
[self.view addSubview:signBtn];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 120, self.view.bounds.size.width - 100, 100)];
view.backgroundColor = [UIColor colorWithRed:20/255.0 green:31/255.0 blue:51/255.0 alpha:0.75];
[self.view addSubview:view];
view.layer.mask = [self drawWithView:view withSignBtnFrame:signBtn.frame];
}
按照点绘制的具体方法,这是创建了一个CAShapeLayer
- (CAShapeLayer *)drawWithView:(UIView *)view withSignBtnFrame:(CGRect)signBtnFrame
{
CGFloat viewWidth = CGRectGetWidth(view.frame);
CGFloat viewHeight = CGRectGetHeight(view.frame);
CGFloat topSpace = 5;
//原点
CGPoint point1 = CGPointMake(0, topSpace);
//三角左边的点
CGPoint point2 = CGPointMake(CGRectGetMinX(signBtnFrame) - 50 + (CGRectGetWidth(signBtnFrame) - 11) / 2, topSpace);
//三角顶点
CGPoint point3 = CGPointMake(CGRectGetMidX(signBtnFrame) - 50, 0);
//三角右边的点
CGPoint point4 = CGPointMake(CGRectGetMaxX(signBtnFrame) - (CGRectGetWidth(signBtnFrame) - 11) / 2 - 50, topSpace);
CGPoint point5 = CGPointMake(viewWidth, topSpace);
CGPoint point6 = CGPointMake(viewWidth, viewHeight);
CGPoint point7 = CGPointMake(0, viewHeight);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:point1];
[path addLineToPoint:point2];
[path addLineToPoint:point3];
[path addLineToPoint:point4];
[path addLineToPoint:point5];
[path addLineToPoint:point6];
[path addLineToPoint:point7];
[path closePath];
CAShapeLayer *layer = [CAShapeLayer layer];
layer.path = path.CGPath;
return layer;
}
另附代码传送门,可运行看效果 :传送门