使用Quartz 2d / CGContext和缩放绘图时出现问题

时间:2011-07-25 14:21:34

标签: ios ipad ios4 uiscrollview quartz-2d

现在我们有一个UIScrollView,它有一个子视图,一个UIView。这个UIView拥有两个UIImageView子视图,一个是静态背景图像。第二个UIImageView是一个供用户使用的视图,我们使用CGContext处理它。

我们使用的是scrollview,因为背景图片和绘图区域很大。当用户选择进入绘图模式的按钮时,他们可以用两根手指滑动以滚动并使用一根手指进行绘制。一切正常。

问题是当我们离开绘图模式并尝试放大时。背景图像完美缩放,但是在它上面绘制UIImageView会做一些奇怪的事情。它将保持正常大小几秒钟,消失,然后突然出现在缩放的大小。所以它正在放大,但有一些非常奇怪的行为和延迟之前。

供参考,以下是我们处理图纸的方法。

/**
 When the user first starts moving the pen
 */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    isMouseMoved = YES; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentPoint = [touch locationInView:imageView]; 

    // Setting up the context
    UIGraphicsBeginImageContext(imageView.frame.size);
    [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];

    if(isEraserOn){
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), eraserRadius);
        CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
        CGRect eraserFrame = eraser.frame; 
        eraserFrame.origin.x = currentPoint.x - (eraserRadius/2);
        eraserFrame.origin.y = currentPoint.y - (eraserRadius/2);
        eraser.frame = eraserFrame;

    }else{
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), penRadius);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), r, g, b, 1.0); 
        CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeNormal);
    }

    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());

    imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    lastPoint = currentPoint; 
    mouseMoved++; 

    if (mouseMoved == 1) {
        mouseMoved = 0;
    } 
} 

有没有人知道我们的绘图UIImageView发生了什么?我们认为延迟可能是由于放大时的抗锯齿,但我们尝试禁用它,我们仍然遇到同样的问题。

1 个答案:

答案 0 :(得分:0)

问题,可能就是说,你在touchesMoved方法中做了所有的绘图,而不是在DrawRect中做,并调用setNeedsDisplay方法来调用你想要的绘图。在来自wwdc 2011的精彩视频中,已经清楚地解释了在诸如touchesMoved或tochesBegan等方法中抓取CGContext是与绘图相关的问题的最常见原因之一。所以我建议你:  1)不要在tochesMoved中调用UIGraphicsGetCurrentContext(),而是在用户绘制的UIView的DrawRect方法中执行。在touchesMoved中,您可以简单地保存被触摸的点,也可以在DrawRect中绘制线条  2)在touchesMoved结束时将setNeedsDisplay消息发送到UIView。这将确保每次调用touchesMoved时UIView都会刷新,并可能会缩短响应时间。你可以尝试一下,甚至不用尝试(1)

希望这有帮助!