【问题标题】:Check when user slides over UIView - touchesMoved too laggy检查用户何时滑过 UIView - touchesMoved 太滞后
【发布时间】:2013-03-03 17:46:00
【问题描述】:

我知道有更好的方法来使用 CoreGraphics 实现绘图工具等等,我使用这种 UIView 方法是因为我想实现像素化效果,而且我还有一些其他自定义的东西会是仅使用内置的 CG 代码很难做到。



我有一个包含 400 个 UIView 的网格来创建我的像素画布......
用户选择一种油漆颜色并开始在 400 个 UIView 的画布上拖动手指,当他们的手指碰到一个 UIView 时,该 UIView 的颜色(也称为像素)将更改为用户选择的颜色...

现在我已经编写了整个代码并且一切正常,但是它很滞后(因为我使用的是 touchesMoved)并且很多点都被跳过了......



我目前正在使用 touchesMoved 并将 UIView 移动到手指位置(我称之为fingerLocationRect)。

当我更新像素(400 个微型 UIView 中的 1 个)颜色时,我通过检查 fingerLocationRect 是否是我的任何一个 UIView 矩形的交集来做到这一点。如果是,我会更新颜色。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];
    fingerLocationRect.center = CGPointMake(currentPosition.x, currentPosition.y);
    int tagID = 1;
    while (tagID <= 400) {
        if(CGRectIntersectsRect(fingerLocationRect.frame, [drawingView viewWithTag:tagID].frame)) {
            [drawingView viewWithTag:tagID].backgroundColor = [UIColor colorWithRed:redVal/255.f green:greenVal/255.f blue:blueVal/255.f alpha:1.f];
        }
        tagID ++;
    }
}



问题是 touchesMoved 不经常更新......所以如果我在画布上拖动手指,只会有 5 个像素发生变化,而不是我实际触摸的 40 个。



我想知道使用CGRectIntersectsRecttouchesMoved 是否是检测用户是否滑动 UIView 的最佳方法...现在它的更新速度不够快,我在左边得到结果而不是右边的结果。 (如果我非常缓慢地移动手指,我只能达到右侧的效果......)



综上所述,除了使用touchesMoved 之外,是否有一种方法可以检测用户何时滑过 UIView?如果没有,关于如何在 touchesMoved 返回的触摸位置之间获取所有 UIView 的任何想法?我让它们都有 1-400 的标签(第一行是 1-10,第二行是 11-21,等等)

附:如果panGestureRecognizertouchesMoved 更频繁地更新?


要了解 400 个 UIView 在这里的样子,它们都带有基于 arc4random 的颜色:





【问题讨论】:

    标签: ios objective-c uiview pixel touchesmoved


    【解决方案1】:

    每次调用 touchesMoved: 时都会循环 400 个视图。您只需要做一些数学运算来确定网格中的哪个视图被触摸。假设 drawingView 是包含所有 400 个“像素”的“画布”视图,并且标签从左上角到右下角排序,那么:

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];    
        CGPoint point = [touch locationInView:drawingView];
        NSInteger column = floorf(20 * point.x / drawingView.bounds.size.width); //20 is the number of column in the canvas
        NSInteger row = floorf(20 * point.y / drawingView.bounds.size.height); //20 is the number of rows in the canvas
        [viewWithTag:column + 20*row].backgroundColor = [UIColor colorWithRed:redVal/255.f green:greenVal/255.f blue:blueVal/255.f alpha:1.f];
    }
    

    这种方法性能改进将允许 cocoa 更频繁地调用 touchesMoved:

    【讨论】:

    • 太棒了!! :) :) :) :) 这实际上是一种我可以应用到我正在开发的基于图块的游戏的方法哈哈!
    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多