在UIImageView中绘制线条

时间:2014-08-10 03:29:26

标签: ios objective-c uiimageview

我有一个UIImageView(wImage),我正在尝试绘制一条线。代码在模拟器中运行良好,但是当我测试它是一个设备时它超级慢并创建一个内存警告。有人可以告诉我这是什么问题吗?

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

UITouch *touch = [touches anyObject];
CGPoint thirdPoint = lastPoint;
lastPoint = [touch previousLocationInView:self.view];
CGPoint currentPoint = [touch locationInView:self.view];

CGPoint mid1 = CGPointMake((lastPoint.x+thirdPoint.x)/2, (lastPoint.y+thirdPoint.y)/2);
CGPoint mid2 = CGPointMake((currentPoint.x+lastPoint.x)/2, (currentPoint.y+lastPoint.y)/2);

UIGraphicsBeginImageContext(wImage.frame.size);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), true);
CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), true);
[wImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), mid1.x, mid1.y);
CGContextAddQuadCurveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y, mid2.x, mid2.y);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);

CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

CGContextStrokePath(UIGraphicsGetCurrentContext());
wImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}

1 个答案:

答案 0 :(得分:2)

您遇到了这样的性能问题,因为每次用户的手指移动时,您实际上都在做大量工作来创建新图像。不要直接在图像上绘制,创建一个负责用户绘图的UIView,具有透明背景。你可以用它做很多事情,而且我不可能在这里放置所有代码,但是有一个很棒的教程,有一些非常酷的代码可以在用户绘图时平滑线条。它会产生更好看的路径。这是:

http://code.tutsplus.com/tutorials/smooth-freehand-drawing-on-ios--mobile-13164

继续阅读所有部分 - 了解正在进行的事情,而不仅仅是尝试上一次实施,这将是一件好事。

对于您的实现,请确保视图具有透明背景,以便您可以在下方看到ImageView。