如何使用quartz2d/coregraphics绘制带圆角的三角形

Dan*_*imm 7 core-graphics ios

Aight所以我想画一个这样的三角形:

圆角三角形

目前我正在使用CAShapeLayer的组合并使用UIBezierPath创建路径(代码如下),然后将其应用为另一层的掩码(self.layer,因为我在UIView子类中而不是设置layerclass我这样做,所以我可以保留初始图层)

无论如何代码:

_bezierPath = [[UIBezierPath bezierPath] retain];
#define COS30 0.86602540378
#define SIN30 0.5
[_bezierPath moveToPoint:(CGPoint){self.frame.size.width/2.f-r*SIN30,r*COS30}];
[_bezierPath addArcWithCenter:(CGPoint){self.frame.size.width/2.f,r*COS30*2.f} radius:r startAngle:2*M_PI/3.f endAngle:M_PI/3.f clockwise:YES];
[_bezierPath addLineToPoint:(CGPoint){self.frame.size.width-r*SIN30,self.frame.size.height-r*COS30}];
[_bezierPath addArcWithCenter:(CGPoint){self.frame.size.width-r*SIN30-r,self.frame.size.height-r*COS30} radius:r startAngle:0.f endAngle:-M_PI/3.f clockwise:YES];
[_bezierPath addLineToPoint:(CGPoint){r*SIN30,self.frame.size.height-r*COS30}];
[_bezierPath addArcWithCenter:(CGPoint){r*SIN30+r,self.frame.size.height-r*COS30} radius:r startAngle:4*M_PI/3.f endAngle:M_PI clockwise:YES];
[_bezierPath closePath];
CAShapeLayer *s = [CAShapeLayer layer];
s.frame = self.bounds;
s.path = _bezierPath.CGPath;
self.layer.mask = s;
self.layer.backgroundColor = [SLInsetButton backgroundColorForVariant:SLInsetButtonColorForSLGamePieceColor(_color)].CGColor;
Run Code Online (Sandbox Code Playgroud)

不幸的是结果不是我想要的,而是角落变成小旋钮(好像它变得太多了)

提前致谢

Dan*_*imm 14

一个出色的朋友(John Heaton,如果遇到他,他非常棒)让我想起核心图形部署的lineCap和lineJoin属性.

某处:

#define border (10.f)
Run Code Online (Sandbox Code Playgroud)

在你的界面:

@property (nonatomic, strong) UIBezierPath *bezierPath;
Run Code Online (Sandbox Code Playgroud)

在你的init中,创建一个这样的短路径:

CGFloat inset = border / 2.f;
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint:(CGPoint){ self.frame.size.width/2.f, inset }];
[bezierPath addLineToPoint:(CGPoint){ self.frame.size.width - inset, self.frame.size.height - inset }];
[bezierPath addLineToPoint:(CGPoint){ a, self.frame.size.height - a }];
[bezierPath closePath];

self.bezierPath = bezierPath;
Run Code Online (Sandbox Code Playgroud)

然后在您的drawRect:方法中执行以下操作:

CGContextRef c = UIGraphicsGetCurrentContext(), context = c;
CGColorRef col = [UIColor redColor].CGColor;
CGColorRef bcol = [UIColor redColor].CGColor;
CGContextSetFillColorWithColor(c, col);
CGContextSetStrokeColorWithColor(c, bcol);
CGContextSetLineWidth(c, border);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetLineCap(c, kCGLineCapRound);
CGContextAddPath(c, self.bezierPath.CGPath);
CGContextStrokePath(c);
CGContextAddPath(c, self.bezierPath.CGPath);
CGContextFillPath(c);
Run Code Online (Sandbox Code Playgroud)

这将在三角形上正确地给你圆角,也可以选择有边框或轮廓