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

时间:2012-11-24 04:27:02

标签: ios core-graphics

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

rounded triangle

目前我正在使用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;

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

提前致谢

1 个答案:

答案 0 :(得分:14)

一位才华横溢的朋友(John Heaton,如果遇到他,他非常棒),让我想起了核心图形部署的lineCap和lineJoin属性。

某处:

#define border (10.f)

在您的界面中:

@property (nonatomic, strong) UIBezierPath *bezierPath;

在你的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;

然后在您的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);

这样可以正确地为您提供三角形上的圆角,也可以选择具有边框或轮廓

相关问题