Jos*_*hua 0 iphone quartz-graphics
我看到了许多如何使用iPhone SDK绘制圆角矩形的示例.我真正需要的是一个修剪过的角矩形,看起来如下:

谢谢,乔希
(这是根据Jonathan Grynspan的建议编辑的,只需使用辅助函数来创建路径.现在它也允许修剪角的高度与宽度不同.)
这是一个帮助C函数来创建这样一个路径:
// Note: caller is responsible for releasing the returned path
CGPathRef createAngledCornerRectPath(CGRect rect,
CGSize cornerSize,
CGFloat strokeWidth)
{
CGMutablePathRef p = CGPathCreateMutable();
// Make points for the corners
CGFloat inset = strokeWidth/2; // because the stroke is centered on the path.
CGPoint tlc = CGPointMake(CGRectGetMinX(rect) + inset,
CGRectGetMinY(rect) + inset);
CGPoint trc = CGPointMake(CGRectGetMaxX(rect) - inset,
CGRectGetMinY(rect) + inset);
CGPoint blc = CGPointMake(CGRectGetMinX(rect) + inset,
CGRectGetMaxY(rect) - inset);
CGPoint brc = CGPointMake(CGRectGetMaxX(rect) - inset,
CGRectGetMaxY(rect) - inset);
// Start in top left and move around counter-clockwise.
CGPathMoveToPoint(p, NULL, tlc.x, tlc.y+cornerSize.height);
CGPathAddLineToPoint(p, NULL, blc.x, blc.y-cornerSize.height);
CGPathAddLineToPoint(p, NULL, blc.x+cornerSize.width, blc.y);
CGPathAddLineToPoint(p, NULL, brc.x-cornerSize.width, brc.y);
CGPathAddLineToPoint(p, NULL, brc.x, brc.y-cornerSize.height);
CGPathAddLineToPoint(p, NULL, trc.x, trc.y+cornerSize.height);
CGPathAddLineToPoint(p, NULL, trc.x-cornerSize.width, trc.y);
CGPathAddLineToPoint(p, NULL, tlc.x+cornerSize.width, trc.y);
CGPathCloseSubpath(p);
return p;
}
Run Code Online (Sandbox Code Playgroud)
以下是如何在自定义视图的-drawRect:方法中使用它:
- (void)drawRect:(CGRect)rect
{
// Define a few parameters
CGSize cornerSize = CGSizeMake(30.f, 30.f);
CGFloat strokeWidth = 3.f;
CGColorRef strokeColor = [UIColor redColor].CGColor;
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(c, strokeColor);
CGContextSetLineWidth(c, strokeWidth);
// Create the path, add it to the context, and stroke it.
CGPathRef path = createAngledCornerRectPath(rect,
cornerSize,
strokeWidth);
CGContextAddPath(c, path);
CGContextStrokePath(c);
// we are responsible for releasing the path
CGPathRelease(path);
}
Run Code Online (Sandbox Code Playgroud)