iOS Screen Drawing最佳实践

时间:2013-03-04 21:31:21

标签: ios objective-c touch uigesturerecognizer uibezierpath

我正在探索制作一个涂鸦应用程序,用户用手指绘制图片,我遇到了几种不同的方式在屏幕上绘制线条。我见过以下代码:

- (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 = YES;     UITouch * touch = [触及anyObject];     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]];
}

在上一个实现中,我会存储用户拖动的点并在绘制时绘制一条线。虽然因为在用户与应用程序交互时会有大量的绘图,但我觉得这样会有很多开销。但/ / p>

所以我的问题是,有最好的做法/最好的绘画方式吗? Apple是否更喜欢某种特定的方式,以及每种方式的优势/劣势是什么?

1 个答案:

答案 0 :(得分:2)

更好的方法是将用户触摸点用作UIBezierPath上的点。参见第23节WWDC 2012 ... http://developer.apple.com/itunes/?destination=adc.apple.com.16351493766