如何根据iOS上的touchMove事件在屏幕上绘制动态矩形
矩形将被视为两个点,第一个点将是touchBegan点,而touchMove将是第二个点,矩形将根据用户手指移动动态绘制,(就像当您单击桌面上的一个单击并移动鼠标你会得到动态矩形)。
谢谢
好的,这里是你如何在touchesMoved
绘制你的矩形(使用@Nekto touchesBegan
存储你的rect的起点)。
让我们假设您在我们正在绘制的UIView上保留一个引用并将其drawnView
。 在touchesBegan
,我们为drawnView
设置框架的drawnView
这里是touchesMoved
:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent*)event { // We only take care of a single touch if ([touches count] == 1) { UITouch *touch = [touches anyObject]; // Find the width and height of the rect CGRect drawnFrame = drawnView.frame drawnFrame.size.width = [touch locationInView:parentView].x - drawnFrame.origin.x drawnFrame.size.height = [touch locationInView:parentView].y - drawnFrame.origin.y [drawnView setFrame:drawnFrame]; } }
不要复制粘贴代码,我没有用Xcode或其他东西写。 它可能有错误(当然)。 但我希望它可以帮助您找到解决方案。 小心,如果你将手指拖到顶部或左侧(高度和宽度的负值),我不知道它会如何表现。
- 您应该定义
UIView
子类,例如,DrawingView
-
在
DrawingView
您应该实现以下方法:保存方法中的起始点:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
在这里重绘rect
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
在这里隐藏(或保存)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
,这里- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
例如,在第一种方法中,您可以通过以下方式检测起点:
CGPoint startCornerOfYourRect; for (UITouch *touch in touches) { startCornerOfYourRect = [touch locationInView:self]; break; }