且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据iOS上的touchMove事件在屏幕上绘制动态矩形

更新时间:2021-09-06 22:38:54

好的,这是在touchesMoved中绘制矩形的方法(使用@Nekto touchesBegan存储矩形的起点).

Okay here is how you can draw your rect in touchesMoved (use @Nekto touchesBegan to store the starting point of your rect).

假设您在我们正在绘制的UIView上保留了一个引用,并将其称为drawnView. 在touchesBegan中,我们为drawnView

Let's assume you keep a reference on the UIView we are drawing and call it drawnView. In touchesBegan, we set the origin of the frame for 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或其他任何东西编写它.它可能有错误(肯定).但我希望它可以帮助您找到解决方案.而且请注意,如果您将手指拖到顶部或左侧(高度和宽度的负值),我将无法知道它的行为.

Don't copy paste that code, I didn't write it in Xcode or anything. It could have mistakes (for sure). But I hope it can help to find your solution. And be careful, I can't tell how it will behave if you drag your finger to the top, or to the left (negative values for height and width).