【发布时间】:2014-04-06 08:04:33
【问题描述】:
正如在之前的 StackOverflow 问题中向我建议的那样,我正在尝试改进我的绘图方法,以便让我的用户将线条/点绘制到 UIView 中。我现在尝试使用 CAShapeLayer 而不是 dispatch_async 进行绘制。这一切都正常工作,然而,在触摸移动时连续绘制到 CAShapeLayer 变得缓慢并且路径滞后,而我的旧(我被告知效率低下)代码运行得非常流畅和快速。您可以在下面看到我的旧代码。
有什么方法可以提高我想做的事情的性能吗?可能是我想多了。
如果能提供任何帮助,我将不胜感激。
代码:
@property (nonatomic, assign) NSInteger center;
@property (nonatomic, strong) CAShapeLayer *drawLayer;
@property (nonatomic, strong) UIBezierPath *drawPath;
@property (nonatomic, strong) UIView *drawView;
@property (nonatomic, strong) UIImageView *drawingImageView;
CGPoint points[4];
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
self.center = 0;
points[0] = [touch locationInView:self.drawView];
if (!self.drawLayer)
{
CAShapeLayer *layer = [CAShapeLayer layer];
layer.lineWidth = 3.0;
layer.lineCap = kCALineCapRound;
layer.strokeColor = self.inkColor.CGColor;
layer.fillColor = [[UIColor clearColor] CGColor];
[self.drawView.layer addSublayer:layer];
self.drawView.layer.masksToBounds = YES;
self.drawLayer = layer;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
self.center++;
points[self.center] = [touch locationInView:self.drawView];
if (self.center == 3)
{
UIBezierPath *path = [UIBezierPath bezierPath];
points[2] = CGPointMake((points[1].x + points[3].x)/2.0, (points[1].y + points[3].y)/2.0);
[path moveToPoint:points[0]];
[path addQuadCurveToPoint:points[2] controlPoint:points[1]];
points[0] = points[2];
points[1] = points[3];
self.center = 1;
[self drawWithPath:path];
}
}
- (void)drawWithPath:(UIBezierPath *)path
{
if (!self.drawPath)
{
self.drawPath = [UIBezierPath bezierPath];
}
[self.drawPath appendPath:path];
self.drawLayer.path = self.drawPath.CGPath;
[self.drawLayer setNeedsDisplay];
// Below code worked faster and didn't lag behind at all really
/*
dispatch_async(dispatch_get_main_queue(),
^{
UIGraphicsBeginImageContextWithOptions(self.drawingImageView.bounds.size, NO, 0.0);
[self.drawingImageView.image drawAtPoint:CGPointZero];
[self.inkColor setStroke];
[path stroke];
self.drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
});
*/
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (self.center == 0)
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:points[0]];
[path addLineToPoint:points[0]];
[self drawWithPath:path];
}
self.drawLayer = nil;
self.drawPath = nil;
}
【问题讨论】:
-
前几天我在这里发布了一个 WWDC 视频的链接。可能对你有用吗? stackoverflow.com/questions/22011115/…
-
感谢您的链接,它有帮助。我能够使用分析器确定 86% 的 CPU 正在执行 [self.drawPath appendPath:path];但不知道如何解决。
标签: ios uiview calayer uibezierpath cashapelayer