以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;
}
(當然也可以半圓等其他形狀的UIBezierPath)