【发布时间】:2016-06-05 05:23:33
【问题描述】:
所以这就是发生的事情: 当我画的时候,贝塞尔线非常平滑。我应用了制作控制点和端点的概念,以使平滑成为可能。但是,我找不到导致延迟的问题。
当我画画时,我会检查我的 CPU 使用率,它会在 5 秒内从大约 50% 变为 90%。我确保当我完成绘图时,我的点会被擦除,同时会创建一个缓冲区来创建我所绘制的图像。
我的猜测是在touchesMoved中同时绘制了太多点?必须有一些点被填充,程序可能无法处理。
#import "SmoothedBIView.h"
@implementation SmoothedBIView
{
UIBezierPath *path;
UIImage *incrementalImage;
CGPoint pts[5]; // need to keep track of the four points of a Bezier segment and the first control point of the next segment
uint ctr;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder])
{
[self setMultipleTouchEnabled:NO];
[self setBackgroundColor:[UIColor whiteColor]];
path = [UIBezierPath bezierPath];
[path setLineWidth:2.0];
}
return self;
}
/* - (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setMultipleTouchEnabled:NO];
path = [UIBezierPath bezierPath];
[path setLineWidth:2.0];
}
return self;
}
*/
animation.
- (void)drawRect:(CGRect)rect
{
[incrementalImage drawInRect:rect];
[path stroke];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
ctr = 0;
UITouch *touch = [touches anyObject];
pts[0] = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
ctr++;
pts[ctr] = p;
if (ctr == 4)
{
pts[3] = CGPointMake((pts[2].x + pts[4].x)/2.0, (pts[2].y + pts[4].y)/2.0); // move the endpoint to the middle of the line joining the second control point of the first Bezier segment and the first control point of the second Bezier segment
[path moveToPoint:pts[0]];
[path addCurveToPoint:pts[3] controlPoint1:pts[1] controlPoint2:pts[2]]; // add a cubic Bezier from pt[0] to pt[3], with control points pt[1] and pt[2]
[self setNeedsDisplay];
// replace points and get ready to handle the next segment
pts[0] = pts[3];
pts[1] = pts[4];
ctr = 1;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self drawBitmap];
/*[self setNeedsDisplay]; */
[path removeAllPoints];
ctr = 0;
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
- (void)drawBitmap
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0);
if (!incrementalImage)
{
UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds];
[[UIColor whiteColor] setFill];
[rectpath fill];
}
[incrementalImage drawAtPoint:CGPointZero];
[[UIColor blackColor] setStroke];
[path stroke];
incrementalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
@end
【问题讨论】:
-
当您说滞后时,您指的是恒定滞后(这是您的算法的自然结果,即每四个点绘制一次)?还是您指的是随着用户按住手指而变得越来越长的延迟(因为您仅在手势完成时才重建图像快照)。这两个都是问题,但我不确定你指的是哪个。
-
也许切换到
CGPath和CGImage会更有效,但除非你测量,否则很难说。 -
@Rob 这是一个持续的延迟。
-
那么我个人 (a) 不会等到
ctr变为4,而是在每次触摸时更新路径; (b) 使用预测性触摸。我也会考虑使用CAShapeLayer,因为据称这比简单的drawRect实现更快。
标签: ios objective-c uibezierpath