iOS 屏幕绘图最佳实践

Posted

技术标签:

【中文标题】iOS 屏幕绘图最佳实践【英文标题】:iOS Screen Drawing best practice 【发布时间】:2013-03-04 21:31:20 【问题描述】:

我正在探索制作一个用户用手指绘制图片的涂鸦应用程序,我遇到了几种不同的在屏幕上画线的方法。我在任何地方都看到过代码:

- (void)drawRect:(CGRect)rect // (5)

    [[UIColor blackColor] setStroke];
    [path stroke];

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path moveToPoint:p];

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

    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path addLineToPoint:p]; // (4)
    [self setNeedsDisplay];

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

    [self touchesMoved:touches withEvent:event];

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

    [self touchesEnded:touches withEvent:event];

到:

mouseSwiped = 是; UITouch *touch = [触摸任何对象]; CGPoint currentPoint = [touch locationInView:self.view];

UIGraphicsBeginImageContext(self.view.frame.size);
[self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

CGContextStrokePath(UIGraphicsGetCurrentContext());
self.tempDrawImage.image = UIGraphicsGetImageFromCurrentImageContext();
[self.tempDrawImage setAlpha:opacity];
UIGraphicsEndImageContext();

lastPoint = currentPoint;

最后一种方法(我想出的方法至少对我来说最有意义)

- (void) viewDidLoad
UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(drawImage:)];
[self.view addGestureRecognizer:pan];
pan.delegate = self;
paths = [[NSMutableArray alloc]init];

- (void) drawImage:(UIPanGestureRecognizer*)pan
CGPoint point = [pan translationInView:self.view];

[paths addObject:[NSValue valueWithCGPoint:point]];

在最后一个实现中,我将存储用户拖动的点并在他们绘制时绘制一条线。我觉得这会有点密集,而且开销很大,因为在用户与应用程序交互时会进行大量绘图。

所以我的问题是,是否有最佳实践/最佳绘画方式? Apple 是否更喜欢一种特定的方式,每种方式的优点/缺点是什么?

【问题讨论】:

【参考方案1】:

更好的方法是使用用户接触点作为UIBezierPath 上的点。请参阅 233 届 WWDC 2012...http://developer.apple.com/itunes/?destination=adc.apple.com.16351493766

【讨论】:

以上是关于iOS 屏幕绘图最佳实践的主要内容,如果未能解决你的问题,请参考以下文章

UIView 绘图最佳实践

ios 轮换最佳实践

最佳实践:iOS - 将单词拖入 Circe?

IOS SDK - xcode interface builder - 管理许多对象的最佳实践是啥?

在所有 ViewControllers swift ios 11 中添加背景图像的最佳实践

什么是 NSManagedObjectContext 最佳实践?