2

我有一个视图,当用户在 iPad/iPhone 的屏幕上移动手指时,我画了一条虚线。我在存储为 LastLocation 的点和作为 CurrentLocation 的点之间画了一条线。图纸要在屏幕上永久显示。每次触发 touchMoved 事件时都会发生这种情况,并最终让我画一条虚线来跟踪人们拖动手指的位置......就像绘画应用程序一样。

我有一个被调用的函数,它在触发触摸事件时执行以下操作。该视图包含一个名为 drawImage 的 UIImageView。我使用 UIImageView 作为持久绘制线条的一种方式。这显然不是人们通常做油漆应用的方式,因为它很慢。任何对使用 CGContextRef 调用进行持久绘画的更好方法的见解将不胜感激。

/* Enter bitmap graphics drawing context */
UIGraphicsBeginImageContext(frame.size);
/* Draw the previous frame back in to the bitmap graphics context */
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)]; //originally self.frame.size.width, self.frame.size.height)];       
/* Draw the new line */
CGContextRef ctx = UIGraphicsGetCurrentContext();
/* Set line draw color to green, rounded cap end and width of 5 */
CGContextSetLineDash(ctx, 0, dashPattern, 2);
CGContextSetStrokeColorWithColor(ctx, color);
CGContextSetLineCap(ctx, kCGLineCapRound); //kCGLineCapSquare, kCGLineCapButt, kCGLineCapRound
CGContextSetLineWidth(ctx, 5.0); // for size
/* Start the new path point */
CGContextMoveToPoint(ctx, LastLocation.x, LastLocation.y);
CGContextAddLineToPoint(ctx, Current.x, Current.y);
CGContextStrokePath(ctx);
/* Push the updated graphics back to the image */
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

'drawImage.image drawInRect' 调用非常慢,本质上是重绘整个图像。

有没有更快的方法来做到这一点?我在绘画博客的几个地方看到过这样的绘图代码,但它有点慢。很想听听关于这个话题的一些想法。

4

1 回答 1

1

无需手动合成图像和线条。拥有在另一个绘制图像的 UIImageView 上方绘制线条的视图。让系统进行合成并绘制图像。

在您的代码中,只需在画线视图的 drawRect: 方法中的两条 drawImage 线之间进行操作。

-(void) drawRect:(CGRect)dirty {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    /* Set line draw color to green, rounded cap end and width of 5 */
    CGContextSetLineDash(ctx, 0, dashPattern, 2);
    CGContextSetStrokeColorWithColor(ctx, color);
    CGContextSetLineCap(ctx, kCGLineCapRound); //kCGLineCapSquare, kCGLineCapButt, kCGLineCapRound
    CGContextSetLineWidth(ctx, 5.0); // for size
    /* Start the new path point */
    CGContextMoveToPoint(ctx, LastLocation.x, LastLocation.y);
    CGContextAddLineToPoint(ctx, Current.x, Current.y);
    CGContextStrokePath(ctx);
}

当线条的一端移动时,保存新的点并将线条图视图标记为需要显示。所以Current和LastLocation都应该是画线视图的成员,并且在每个的setter方法中,调用setNeedsDisplay。

确保 clearsContextBeforeDrawing 是 YES 并且 opaque 是 NO 对于线条绘制视图。

于 2010-07-03T06:52:42.030 回答