这里的新程序员尝试按部就类。我正在尝试找到一种方法来围绕设备上每个当前触摸的位置画一个圆圈。两根手指在屏幕上,每根手指下一个圆圈。
我目前有在一个触摸位置绘制圆圈的工作代码,但是一旦我将另一根手指放在屏幕上,圆圈就会移动到第二个触摸位置,而第一个触摸位置为空。当我添加第三个时,它会移动到那里等等。
理想情况下,我希望屏幕上最多有 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 的 didFinishLaunchingWithOptions
方法中声明了 setMultipleTouchEnabled:YES
。
我试图在 drawTouchCircle
方法中使用 if 语句,将 self.firstTouch.x
更改为 self.secondTouch.x
基于 self.tapCount
但这似乎打破了整个事情,让我在任何触摸位置都没有圆圈。
我很难找到我的问题,我知道这可能很简单。
最佳答案
我刚刚写了一些似乎有效的代码。我在 View 中添加了一个名为 circles
的 NSMutableArray
属性,其中包含每个圆的 UIBezierPath
。
在 -awakeFromNib
中,我设置了数组并设置了 self.multipleTouchEnabled = YES
-(我认为您是使用对 appDelegate.m 中的 View 的引用来完成此操作的)。
在 View 中,我在 -touchesBegan
和 -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];
}
然后我在 -drawRect
中遍历 circles
并在每个圆上调用 [circle stroke]
关于ios - 如何在设备上的每个触摸位置周围绘制一个圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14917090/