如何实现多边形按钮、View超出部分没有点击效果
以UIButton为例。创建一个类继承UIButton,给一个外部的属性shapePath。当给shapePath赋值的时候
创建CAShapeLayer,作为遮掩图层。
hitTest:withEvent: 在这个方法里面进行判断点击的点是否在显示的区域内,实现超出部分点击不到。
.h文件
#import@interface ShapeButton : UIButton
@property(nonatomic , strong)UIBezierPath *shapePath;
@end
#import "ShapeButton.h"
@implementation ShapeButton
{
CAShapeLayer *shapeLayer;
}
-(void)setShapePath:(UIBezierPath *)shapePath{
_shapePath=shapePath;
if (_shapePath==nil) {
self.layer.mask=nil;
return;
}
if (!shapeLayer) {
shapeLayer=[CAShapeLayer layer];
}
shapeLayer.path=_shapePath.CGPath;
self.layer.mask=shapeLayer;
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
if (_shapePath&&[_shapePath containsPoint:point]==NO) {
return nil;
}
return [super hitTest:point withEvent:event];
}
@end
2.如何绘制正多边形
-(UIBezierPath *)width:(CGFloat )width center:(CGPoint)center lineCount:(NSInteger)count{
UIBezierPath *auxiliaryPath=[UIBezierPath bezierPath];
UIBezierPath *path=[UIBezierPath bezierPath];
[auxiliaryPath moveToPoint:CGPointMake(center.x+width, center.y)];
[path moveToPoint:auxiliaryPath.currentPoint];
for (int i=0; i<count;i++){
[auxiliaryPath addArcWithCenter:center radius:width startAngle:2*M_PI/(count*1.0)*i endAngle:2*M_PI/(count*1.0)*(i+1) clockwise:YES];
[path addLineToPoint:auxiliaryPath.currentPoint];
}
return path;
}
在VC中调用(当然也可以半圆等其他形状的UIBezierPath)