如何在用户手指移动后画线

Posted

技术标签:

【中文标题】如何在用户手指移动后画线【英文标题】:How to draw line following user finger move 【发布时间】:2014-05-29 12:16:53 【问题描述】:

代码:

- (void)drawRect:(CGRect)rect

    CGContextRef context = UIGraphicsGetCurrentContext();
    UIColor *grayColor = [UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0];

    [grayColor set];

    CGContextSetLineWidth(context, 2.0);
    CGContextStrokeEllipseInRect(context, CGRectMake(100, 190, 101, 101));

我确实画了一个圆圈。当用户在上面移动手指时,我想在上面画线。我在谷歌上搜索了很多关于这个的内容。但我找不到任何解决方案。任何帮助将不胜感激。提前致谢。

【问题讨论】:

查看***.com/questions/16846413/… 请查看raywenderlich.com/18840/… cocoacontrols.com/controls/jbsignaturecontroller 【参考方案1】:

你应该看看这些:

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

这些是跟踪UIView 触摸的方法。

【讨论】:

【参考方案2】:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

        UITouch *touch = [touches anyObject];
        CGPoint tapLocation = [touch locationInView:self.superDrawingLayer];  
        lastPoint = tapLocation;


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
        UITouch *touch = [touches anyObject];
        CGPoint tapLocation = [touch locationInView:self.superDrawingLayer];
        currentPoint = tapLocation;

        UIGraphicsBeginImageContext(self.superDrawingLayer.frame.size);
        [self.superDrawingLayer.image drawInRect:CGRectMake(0, 0, self.superDrawingLayer.frame.size.width, self.superDrawingLayer.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), drwaingWidth);
        CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeColor);
        CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:1.0f green:0.764705f blue:0 alpha:1.0] CGColor]);
        CGContextBeginPath(UIGraphicsGetCurrentContext());
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        CGContextFlush(UIGraphicsGetCurrentContext());


        self.superDrawingLayer.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        lastPoint = tapLocation;


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


//这里的superDrawingLayer是要在上面画线的ImageView。

【讨论】:

以上是关于如何在用户手指移动后画线的主要内容,如果未能解决你的问题,请参考以下文章

在用户想要画线时获取 CGPoint 数组

沿着滑动路径用箭头在滑动手指上画线

当用户在屏幕上滑动手指时,如何使我的页面滑动?

如何使用 Core Graphics 绘制箭头?

当手指在 iPhone 上移动时如何在图像顶部画一条线

如何触摸 UIImageView,然后用另一个 UIImageView 替换,当手指移动时它会拖动,而不用抬起手指