【问题标题】:iOS: How to draw a line between two moving objects?iOS:如何在两个移动的物体之间画一条线?
【发布时间】:2013-03-11 04:43:00
【问题描述】:

我基本上在屏幕上有一组 UIView 对象。它们被随机移动,我想用一条线连接每个对象。

在包含所有移动对象的 UIView 的 drawRect 方法中,我在它们之间绘制线条。然后一旦完成,就会为每个对象调用以下方法

-(void)animateIcon:(Icon*)icon{
[UIView animateWithDuration:(arc4random() % 100 * 0.1)
                      delay: 0.0
                    options: UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     icon.frame = CGRectMake((arc4random() % 320), (arc4random() % ((int)self.frame.size.height - 70)), 52, 52);
                 }
                 completion:^(BOOL finished){[self animateIcon:icon];}];

}

基本上我希望线条在移动时保持附着在物体上。如果我可以调用 [self setNeedsDisplay];每次框架发生变化时,drawRect 方法都会重新绘制线条,但我不知道如何做到这一点。

我尝试在帧变化上设置一个观察者(如下所示),但它只会在动画完成后触发,并且不会捕捉到帧变化,因为对象处于动画中间

[icon addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld context:NULL];

有人有什么想法吗??

【问题讨论】:

    标签: iphone ios animation drawing drawrect


    【解决方案1】:

    将所有移动视图放在一个数组中

    [UIView setAnimationDidStopSelector:@selector(animationStopped:isFinished:context:)];
    
    
    - (void)animationStopped:(NSString*)animationID isFinished:(BOOL)finished context:(void *)context 
    {
        context = UIGraphicsGetCurrentContext() ;
        CGContextSaveGState(context);
        CGContextSetStrokeColorWithColor(context,[UIColor blueColor].CGColor );
        CGContextSetLineWidth(myContext, 5.0);
         CGMutablePathRef myPathRef = CGPathCreateMutable() ;
         for (int ind = 0 ; ind < [movingViewArray count] ; ind++)
           {
              UIView *tmpView=[movingViewArray objectAtIndex:ind];
              CGPoint point=tmpView.frame.center;
             if(ind==0) CGPathMoveToPoint(myPathRef, nil, point.x, point.y);
              else {
                     CGPathAddLineToPoint(myPathRef, nil, point.x, point.y);
                     CGPathMoveToPoint(myPathRef, nil, point.x, point.y);
                    }
            }
    
          CGContextAddPath(context, myPathRef) ;
    
          CGPathRelease(myPathRef);
    
          CGContextDrawPath(context,kCGPathStroke);
          CGContextClip(context);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      相关资源
      最近更新 更多