在 UIButton 中创建三角形
Posted
技术标签:
【中文标题】在 UIButton 中创建三角形【英文标题】:Creating a triangle shape in a UIButton 【发布时间】:2014-07-15 22:12:23 【问题描述】:我正在尝试创建一个带有三角形图标/形状的按钮。我在Paintcode
中创建了三角形,然后复制了 beizer 路径并将其添加到按钮层,如下所示。
-(void)setupShowHideRouteButton
UIBezierPath* bezierPath = UIBezierPath.bezierPath;
[bezierPath moveToPoint: CGPointMake(10.5, 8.5)];
[bezierPath addCurveToPoint: CGPointMake(40.5, 8.5) controlPoint1: CGPointMake(39.5, 8.5) controlPoint2: CGPointMake(40.5, 8.5)];
[bezierPath addLineToPoint: CGPointMake(26.39, 22.3)];
[bezierPath addLineToPoint: CGPointMake(25.2, 23.5)];
[bezierPath addLineToPoint: CGPointMake(10.5, 8.5)];
[UIColor.blackColor setStroke];
bezierPath.lineWidth = 1;
[bezierPath stroke];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = self.showHideRouteViewBtn.bounds;
shapeLayer.path = bezierPath.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [UIColor blackColor].CGColor;
shapeLayer.lineWidth = 2;
[self.showHideRouteViewBtn.layer addSublayer:shapeLayer];
但是,这似乎不起作用。我正在设置 UIButton 的背景颜色,所以我知道框架是正确的,并且插座按预期工作,只是没有添加形状?
第二种方法
UIBezierPath* bezierPath = UIBezierPath.bezierPath;
[bezierPath moveToPoint: CGPointMake(10.5, 8.5)];
[bezierPath addCurveToPoint: CGPointMake(40.5, 8.5) controlPoint1: CGPointMake(39.5, 8.5) controlPoint2: CGPointMake(40.5, 8.5)];
[bezierPath addLineToPoint: CGPointMake(26.39, 22.3)];
[bezierPath addLineToPoint: CGPointMake(25.2, 23.5)];
[bezierPath addLineToPoint: CGPointMake(10.5, 8.5)];
[UIColor.blackColor setStroke];
bezierPath.lineWidth = 1;
[bezierPath stroke];
// Create a mask layer and the frame to determine what will be visible in the view.
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
CGRect maskRect = self.showHideRouteViewBtn.bounds;
// Create a path with the rectangle in it.
CGPathRef path = CGPathCreateWithRect(maskRect, NULL);
// Set the path to the mask layer.
maskLayer.path = bezierPath.CGPath;
// Release the path since it's not covered by ARC.
CGPathRelease(path);
// Set the mask of the view.
self.showHideRouteViewBtn.layer.mask = maskLayer;
这也不起作用。
【问题讨论】:
尝试屏蔽图层 如果你设置了shape layer的backgroundColor
,你能确认它在view里面是正确对齐的吗?
@troop231 - 请参阅有问题的第二种方法,这对我也不起作用
请提供您的UIButton
设置代码,以便我查看框架尺寸、颜色等。
【参考方案1】:
尝试以下方法:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = self.showHideRouteViewBtn.bounds;
shapeLayer.path = bezierPath.CGPath;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.strokeColor = [UIColor blackColor].CGColor;
shapeLayer.lineWidth = 2;
self.showHideRouteViewBtn.layer.mask = shapeLayer;
【讨论】:
谢谢,成功了。我还注意到我在解决它的过程中犯的一个愚蠢的错误......太晚了,我的错!谢谢 很高兴它有帮助!请接受 得等 5 分钟,你会明白的 :)以上是关于在 UIButton 中创建三角形的主要内容,如果未能解决你的问题,请参考以下文章