在UIImageView上绘制自定义路径

时间:2014-12-29 01:41:58

标签: ios objective-c uiimageview uigesturerecognizer uibezierpath

我已经在Objective C中编程了几个星期,而我正在制作的一个小型练习iPhone应用程序的功能是在图像上画线。在我的视图控制器的viewDidLoadMethod中我使用

初始化UIPanGestureRecognizer
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
      initWithTarget:self action:@selector(drawLine:)];
[panGestureRecognizer setMinimumNumberOfTouches:1];
[panGestureRecognizer setMaximumNumberOfTouches:1];
[self.imageView addGestureRecognizer:panGestureRecognizer];
panGestureRecognizer = nil;

响应panGestureRecognizer的函数是

- (void)drawLine:(UIPanGestureRecognizer *)panGestureRecognizer {

    CGPoint start = [panGestureRecognizer locationInView:self.imageView];

    CGPoint shift = [panGestureRecognizer translationInView:self.imageView];

    CGPoint final;
    final.x = start.x + shift.x;
    final.y = start.y + shift.y;

    UIBezierPath *path = [[UIBezierPath alloc] init];

    [path moveToPoint:start];

    [path addLineToPoint:final];

    [path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

当我在图像上移动手指时,代码会执行,但不会出现任何线条。我不确定这是否意味着它位于imageView中已经存在的图像后面,或者根本没有被绘制。任何有关如何处理这个问题的帮助将不胜感激,不确定我是否在正确的轨道上。感谢。

1 个答案:

答案 0 :(得分:0)

您没有有效的CGContextRef来绘制,因为您没有在任何绘图周期内执行此代码。

我将这些CGPoints存储在几个变量中,并在视图或图层上调用setNeedsDisplay进行绘制,然后将绘图代码放入其中 - (void)drawRect: