2

我正在尝试setNeedsDisplayInRect:在 iOS5 中使用来优化一些绘图代码。设置很简单:我有一个 CGRect '热点'数组,用作按钮。当检测到触摸时,我找到它发生的 CGRect 并setNeedsDisplayInRect:以该矩形作为参数调用视图。所有的 CGRects 对视图都是有效的——它使用它们来进行初始绘图并且正确显示。

我所看到的(如下面的控制台转储所示)是第一次调用setNeedsDisplayInRect:将视图框架作为矩形传递,而不是我指定的矩形。随后的调用是正确的。

谁能确认这是一个错误或看到我在这里做错了什么?所有代码都在下面。 - 谢谢!

WRONG -> drawRect with rect 0.000000  0.000000  70.000000  660.000000 
drawRect with rect 15.000000  260.000000  40.000000  40.000000 
drawRect with rect 15.000000  310.000000  40.000000  40.000000 
drawRect with rect 15.000000  360.000000  40.000000  40.000000 
drawRect with rect 15.000000  410.000000  40.000000  40.000000 
drawRect with rect 15.000000  460.000000  40.000000  40.000000 
drawRect with rect 15.000000  510.000000  40.000000  40.000000 
drawRect with rect 15.000000  410.000000  40.000000  40.000000 
drawRect with rect 15.000000  310.000000  40.000000  40.000000 
drawRect with rect 15.000000  260.000000  40.000000  40.000000 
drawRect with rect 15.000000  110.000000  40.000000  40.000000 
drawRect with rect 15.000000  610.000000  40.000000  40.000000 
drawRect with rect 15.000000  510.000000  40.000000  40.000000 



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view]; 

    CGRect rect;
    int cnt = self.barNoteArray.count;
    for (int i = 0; i < cnt; i++) {
        rect = [[self.barNoteArray objectAtIndex:i] cellRect];
        if (CGRectContainsPoint(rect, point)) {

            self.bar.highlightIndex = 1;
            [self.bar setNeedsDisplayInRect:rect];

            break;
        }
    }
}



- (void)drawRect:(CGRect)rect
{
if (highlightIndex){

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextAddRect(context, rect);
    CGContextFillPath(context);

    highlightIndex = 0;

    printf("drawRect with rect %f  %f  %f  %f \n", rect.origin.x,
          rect.origin.y,
          rect.size.width,
          rect.size.height);
} else {
  // other drawing code


}
4

1 回答 1

2

我也有这个问题。我已将其缩小到以下情况:

当我从一个 UIView 切换到第二个 UIView 时,似乎正在发生这种情况。在我的例子中,用户在一个 UIView 中选择一个绘画工具,然后在底层 UIView(画布)上绘画。

似乎初始笔画将 drawRect 中收到的矩形从您放入其中的内容更改为完整视图大小。一旦那些一两个 drawRects 被绘制出来,它就不会改变你放在那里的东西。

我可以证明它是一个 setNeedsDisplayInRect ,因为如果我注释掉有问题的行 drawRect 不再被调用。就在调用之前的矩形显示了要更新的正确子矩形,drawRect 中的矩形显示了一个不同的矩形。

同样,这仅发生在从一个 UIView 到另一个 UIView 的初始移动中(似乎)。

于 2012-04-01T00:57:58.073 回答