如何實現多邊形按鈕、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)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容