3

这里的新程序员试图一步一步地做事。我试图找到一种方法在设备上每个当前触摸的位置周围画一个圆圈。两个手指在屏幕上,每个手指下一个圆圈。

我目前有在一个触摸位置画一个圆圈的工作代码,但是一旦我将另一根手指放在屏幕上,圆圈就会移动到第二个触摸位置,而第一个触摸位置是空的。当我添加第三个时,它会移动到那里等等。

理想情况下,我希望屏幕上最多可以有 5 个活动圆圈,每个手指一个。

这是我当前的代码。

@interface TapView ()
@property (nonatomic) BOOL touched;
@property (nonatomic) CGPoint firstTouch;
@property (nonatomic) CGPoint secondTouch;
@property (nonatomic) int tapCount;
@end

@implementation TapView

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];

NSArray *twoTouch = [touches allObjects];
    if(touches.count == 1)
    {
        self.tapCount = 1;
        UITouch *tOne = [twoTouch objectAtIndex:0];
        self.firstTouch = [tOne locationInView:[tOne view]];
        self.touched = YES;
        [self setNeedsDisplay];
    }
    if(touches.count > 1 && touches.count < 3)
    {
        self.tapCount = 2;
        UITouch *tTwo = [twoTouch objectAtIndex:1];
        self.secondTouch = [tTwo locationInView:[tTwo view]];
        [self setNeedsDisplay];
    } 
}
-(void)drawRect:(CGRect)rect
{
        if(self.touched && self.tapCount == 1)
        {
            [self drawTouchCircle:self.firstTouch :self.secondTouch];
        }
}
-(void)drawTouchCircle:(CGPoint)firstTouch :(CGPoint)secondTouch
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(ctx,0.1,0.1,0.1,1.0);
    CGContextSetLineWidth(ctx,10);
    CGContextAddArc(ctx,self.firstTouch.x,self.firstTouch.y,30,0.0,M_PI*2,YES);
    CGContextStrokePath(ctx);
}

我确实在 appDelegate.m 的方法中setMultipleTouchEnabled:YES声明了。didFinishLaunchingWithOptions

我试图在方法中使用一个 if 语句,该语句基于 adrawTouchCircle更改为self.firstTouch.x,但这似乎破坏了整个事情,让我在任何触摸位置都没有圆圈。self.secondTouch.xself.tapCount

我很难找到我的问题,而且我知道这可能很简单。

4

1 回答 1

3

我刚刚写了一些似乎可以工作的代码。我添加了一个NSMutableArray名为circles视图的属性,其中包含UIBezierPath每个圆圈的属性。在-awakeFromNib我设置数组并设置self.multipleTouchEnabled = YES- (我认为您使用对 appDelegate.m 中的视图的引用来完成此操作)。

-touchesBegan在视图中,我在and方法中调用了这个-touchesMoved方法。

-(void)setCircles:(NSSet*)touches
{   
    [_circles removeAllObjects]; //clear circles from previous touch

    for(UITouch *t in touches)
    {
        CGPoint pt= [t locationInView:self];
        CGFloat circSize = 200; //or whatever you need
        pt = CGPointMake(pt.x - circSize/2.0, pt.y - circSize/2.0);
        CGRect circOutline = CGRectMake(pt.x, pt.y, circSize, circSize);
        UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:circOutline];
        [_circles addObject:circle];
    }
    [self setNeedsDisplay];
}

触摸结束是:

-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{ 
    [_circles removeAllObjects];
    [self setNeedsDisplay];

}

然后我循环circles访问-drawRect并调用[circle stroke]每一个

于 2013-02-17T02:17:10.493 回答