我看到了许多如何使用iPhone SDK绘制圆角矩形的示例。我真正需要的是修剪过的角落矩形,其外观如下:
谢谢, 约什
答案 0 :(得分:5)
(这是根据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;
}
以下是您在自定义视图中使用它的方法-drawRect:method:
- (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);
}
答案 1 :(得分:0)
我只使用8个线段(起始路径,添加到路径的行,结束路径,笔划路径)。 您只需要在每个x或y角坐标中添加或减去一些常量,即可得到所有8个点。您可以使用与CGStrokeRect相同的api编写一个简单函数来封装上述所有内容。