简体   繁体   English

iOS:如何在两个移动的物体之间划一条线?

[英]iOS: How to draw a line between two moving objects?

I basically have an array of UIView objects that are on screen. 我基本上在屏幕上有一个UIView对象数组。 They are being moved randomly around and I would like to have a line connecting each object. 它们正在随机移动,我想用一条线连接每个对象。

In my drawRect method of the UIView that contains all the moving objects, I draw the lines between them. 在包含所有移动对象的UIView的drawRect方法中,我绘制了它们之间的线。 Then once that is done the below method is called for each object 然后,一旦完成,将为每个对象调用以下方法

-(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];}];

} }

Essentially I would like the lines to stay attached to the objects as they move. 本质上,我希望线条在对象移动时保持附着。 If I could call [self setNeedsDisplay]; 如果我可以打电话给[self setNeedsDisplay]; every time the frame changed at all, then the drawRect method would re-draw the lines, but I can't figure out how to make this happen. 每次框架完全改变时,drawRect方法都会重新绘制线条,但是我不知道该如何实现。

I tried setting an observer on the frame change (shown below) but it only gets triggered once an animation is finished, and doesn't catch the frame changes as the object is mid-animation 我尝试在帧变化上设置观察者(如下所示),但只有在动画完成后才会触发,并且由于对象处于中间动画状态而无法捕获帧变化

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

any body got any ideas?? 任何人有任何想法吗?

Put all moving views inside one array 将所有移动视图放入一个数组中

[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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM