4

我在屏幕上有 9 个六边形精灵,我必须在它们周围指定一条特定路径以使它们的区域可触摸。我不想分别为每条路径设置坐标,所以我不能只使用第一条路径(六边形都相同大小)并将其原点移动到另一个位置(不破坏形状)吗?(如果我现在这样做,CGPathAddLineToPoint(); 会从前一个六边形中添加六边形的点。我希望我明白这个想法......(见图......注意:右上角的灰色八边形是与黑色完全相同的大小和形状)![移动路径坐标和形状][1]

hex2TouchArea=CGPathCreateMutable();

    CGPathMoveToPoint(hex2TouchArea, NULL, 150,157);
    CGPathAddLineToPoint(hex2TouchArea, NULL, 130, 198);
    CGPathAddLineToPoint(hex2TouchArea, NULL, 146, 236);
    CGPathAddLineToPoint(hex2TouchArea, NULL, 195, 236);
    CGPathAddLineToPoint(hex2TouchArea, NULL, 218, 197);
    CGPathAddLineToPoint(hex2TouchArea, NULL, 193, 157);
    CGPathCloseSubpath(hex2TouchArea);

在这里,我放了一张图片,在图片中显示它
http://666kb.com/i/bz2ysevuw8n65rh3i.gif

*编辑:我从帖子中得到了解决方案并稍作改动:*

-(CGMutablePathRef) drawHexagon:(CGPoint)origin
{
    //create mutable path
    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, nil, origin.x, origin.y);

    CGPoint newloc = CGPointMake(origin.x - 20, origin.y + 42);
    CGPathMoveToPoint(path, NULL, newloc.x, newloc.y);
    CGPathAddLineToPoint(path, NULL, newloc.x + 16,newloc.y + 38);
    CGPathAddLineToPoint(path, NULL, newloc.x + 49, newloc.y + 0);
    CGPathAddLineToPoint(path, NULL, newloc.x + 23,  newloc.y - 39);
    CGPathAddLineToPoint(path, NULL, newloc.x - 25,newloc.y - 40);
    CGPathAddLineToPoint(path, NULL, newloc.x -43, newloc.y + 0);
    CGPathCloseSubpath(path);
    return path;   

}
4

1 回答 1

6

重用路径的最佳方法可能是为它们创建一个方法。在添加起始坐标并返回 CGMutablePathRef 的位置创建一个,以便在路径完成后绘制它。

以下是根据您在问题中输入的示例路径的样子:

-(CGMutablePathRef) drawHexagon:(CGPoint)origin
{
    //create mutable path
    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, nil, origin.x, origin.y);

    CGPoint newloc = CGPointMake(origin.x - 20, origin.y + 42);
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);
    CGPoint newloc = CGPointMake(newloc.x + 16, newloc.y + 38);
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);
    CGPoint newloc = CGPointMake(newloc.x + 49, newloc.y + 0);
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);
    CGPoint newloc = CGPointMake(newloc.x + 23, newloc.y - 39);
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);
    CGPoint newloc = CGPointMake(newloc.x - 25, newloc.y - 40);
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);
    CGPoint newloc = CGPointMake(newloc.x - 43, newloc.y + 0); //which should be you origin
    CGPathMoveToPoint(path, nil, newloc.x, newloc.y);

    CGPathCloseSubpath(path);
    return path;   
}

调用它CGMutablePathRef path = [self drawHexagon:someStartingPoint];


编辑到期评论:

您可以使用以下方法将路径添加到上下文中:CGContextAddPath(context, path); 然后根据您的感觉绘制它,例如:CGContextDrawPath(context, kCGPathFill);

将路径添加到上下文后应该不难。

这应该适合你。祝你好运。

于 2011-11-29T12:23:56.490 回答