7

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;

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

提前致谢

4

1 回答 1

14

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

某处:

#define border (10.f)

在您的界面中:

@property (nonatomic, strong) UIBezierPath *bezierPath;

在你的初始化中,创建一个像这样的短路径:

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);

这将适当地为您提供三角形上的圆角,还可以选择具有边框或轮廓

于 2012-12-20T09:49:38.607 回答