如何在用户手指移动后绘制线条

时间:2014-05-29 12:16:53

标签: ios objective-c

代码:

- (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));
}

我画了一个圆圈。当用户移动手指时,我想在它上画线。我搜索了很多关于此。但是我找不到任何解决方案。任何帮助都会受到赞赏。谢谢提前。

2 个答案:

答案 0 :(得分:0)

你应该看看这些:

- (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

的触摸的方法

答案 1 :(得分:0)

-(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。