[英]How can I draw dynamic rectangle on screen according to touchMove event on iOS
矩形将被视为两个点,第一个点将是touchBegan点,在touchMove上将是第二个点,将根据用户的手指移动来动态绘制矩形(例如,当您在桌面上单击并移动鼠标时鼠标,您将获得动态矩形)。
谢谢
UIView
子类,例如DrawingView
在DrawingView
您应该实现以下方法:
将起点保存在方法中- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
在此处重绘- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
在此处隐藏rect(或将其保存) - (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;
}
好的,这是在touchesMoved
绘制矩形的方法(使用@Nekto touchesBegan
存储矩形的起点)。
假设您在要绘制的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或任何东西编写它。 它可能有错误(肯定)。 但我希望它可以帮助您找到解决方案。 请注意,如果您将手指拖到顶部或左侧(高度和宽度的负值),我将无法知道它的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.