ios - 在 UIImageView 中画线

标签 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();
}

最佳答案

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

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

继续阅读所有部分 - 了解正在发生的事情而不是仅仅尝试最后一个实现对您有好处。

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

关于ios - 在 UIImageView 中画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225255/

相关文章:

objective-c - CTLineGetStringRange 和 CTLineGetGlyphCount 返回的行中字符数错误

iPhone SDK : subFolders inside the main bundle

ios - XCTest 错误 : The bundle couldn’t be loaded. 尝试重新安装 bundle

ios - Facebook Connect Graph API 在成功分享到 Facebook 时收到通知

iphone - KVO机制抛出错误?

ios - NSArray 上的强属性和保留循环

ios - Apple 询问我是否在我的新提交应用程序中包含加密的原因是什么?

iOS 应用程序 : max number of files and impact of 20K small files?

ios - 缩小放置在 UIScrollView 中的 UIImageView

ios - UIImageView 图片名称比较问题