【问题标题】:Problem with touchesMoved and drawRecttouchesMoved 和 drawRect 的问题
【发布时间】:2009-04-21 20:29:04
【问题描述】:

我有一个我似乎无法弄清楚的棘手错误,我认为它与 touchesMoved 的实现方式有关。

在 touchesMoved 中,我检查触摸的位置(if 语句),然后相应地在触摸点附近的 40 x 40 区域调用 setNeedsDisplayWithRect。在 DrawRect 中发生的情况是,如果之前有一个白色图像,则会放下一个黑色图像,反之亦然。在调用 setNeedsDisplayWithRect 的同时,我在布尔数组中设置了一个布尔变量,这样我就可以跟踪当前图像是什么,从而显示相反的图像。 (其实我并不总是翻转图像...我看第一次触摸会做什么,比如从黑色切换到白色,然后在所有后续触摸上放置白色图像,所以有点像绘图或与图像一起删除)。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    CGPoint lastTouchPoint = [touch previousLocationInView:self];

    touchX = touchPoint.x;
    touchY = touchPoint.y;

    int lastX = (int)floor((lastTouchPoint.x+0.001)/40);
    int lastY = (int)floor((lastTouchPoint.y+0.001)/40);
    int currentX  = (int)(floor((touchPoint.x+0.001)/40));
    int currentY  = (int)(floor((touchPoint.y+0.001)/40));

    if  ((abs((currentX-lastX)) >=1) || (abs((currentY-lastY)) >=1))
    {
        if ([soundArray buttonStateForRow:currentX column:currentY] == firstTouchColor){
            [soundArray setButtonState:!firstTouchColor row:(int)(floor((touchPoint.x+0.001)/40)) column:(int)(floor((touchPoint.y+0.001)/40))];

            [self setNeedsDisplayInRect:(CGRectMake((CGFloat)(floor((touchPoint.x+0.001)/40)*40), (CGFloat)(floor((touchPoint.y+0.001)/40)*40), (CGFloat)40.0, (CGFloat)40.0))];
        }
    }
}

我的问题是布尔数组似乎与我放下的图像格格不入。只有当我在屏幕上快速拖动时才会发生这种情况。最终布尔数组和图像不再同步,即使我同时设置它们。知道是什么原因造成的,或者我可以做些什么来解决它?

这是我的drawRect:

- (void)drawRect:(CGRect)rect {

    if ([soundArray buttonStateForRow:(int)(floor((touchX+0.001)/40)) column:(int)(floor((touchY+0.001)/40))])
        [whiteImage drawAtPoint:(CGPointMake((CGFloat)(floor((touchX+0.001)/40)*40), (CGFloat)(floor((touchY+0.001)/40))*40))]; 
    else
        [blackImage drawAtPoint:(CGPointMake((CGFloat)(floor((touchX+0.001)/40)*40), (CGFloat)(floor((touchY+0.001)/40))*40))]; 


}

【问题讨论】:

    标签: objective-c cocoa-touch drawing touch


    【解决方案1】:

    我想出了这个问题的答案。 touchX 和 touchY 是实例变量,在每次调用 drawRect 完成之前,它们在 touchesMoved 中被重置。因此,如果我在屏幕上快速移动,将调用 touchesMoved,然后调用 drawRect,然后在 drawRect 使用 touchX 和 touchY 之前再次调用 touchesMoved,因此绘图将与布尔数组后端不同步。

    为了解决这个问题,我停止在 drawRect 中使用 touchX 和 touchY,并开始使用从 touchesMoved 传入的脏矩形来推导相同的点。

    多多!

    【讨论】:

    • 脏矩形是什么意思?
    猜你喜欢
    • 2011-11-10
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多