0

我有一个名为 UIView 的子类MENode。每个MENode都有一个 NSMutableDictionary 来跟踪它的子节点(也是MENodes)。我想要实现的是从父节点到子节点画一条线。这是我的drawRect:in实现MENode

- (void)drawRect:(CGRect)rect{
//connect the sub node to its super node by drawing a line between the two;

    for (int i=0; i<self.subNodes.count; i++) {
        //get one of the child nodes
        MENode *subNode = [self.subNodes objectAtIndex:i];

        //get the context and set up color and line width
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
        CGContextSetLineWidth(context, 5);

        //set up a line between the parent node and the child node
        CGContextMoveToPoint(context, self.center.x, self.center.y);
        CGContextAddLineToPoint(context, subNode.center.x, subNode.center.y);

        //draw it.
        CGContextStrokePath(context);
    }
}

下面的两个方法都由视图控制器调用。我[self setNeedsDisplay];两个都叫:

-(void)addNode:(MENode *)newNode{
    //set the child node's parent node to self (a weak reference)
    newNode.parentNode = self;

    //add the node to self.subNodes
    [self.subNodes addObject:newNode];

    //add the node to the parent node
    [self addSubview:newNode];

    //call seeNeedsDisplay
    [newNode setNeedsDisplay];
}

-(void)nodeAdditionsDone{
    //call setNeedsDisplay
    [self setNeedsDisplay];

    //do some logic with this later
    self.nodeAddtionsAreFinished = YES;
}

当我运行它时,我没有得到任何线条,只有节点。在此先感谢您的帮助。

4

1 回答 1

1
CGContextMoveToPoint(context, self.center.x, self.center.y);

self.center在视图的superview的坐标空间中,所以这可能是问题的一部分。尝试这个:

CGContextMoveToPoint(context, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))

您可能还想在绘图代码中设置断点,以确保self.subNodes在绘图执行时实际有对象。

于 2014-01-30T23:00:58.390 回答