How do I use UIBezierPath to draw a line that follows a touch event?

后端 未结 1 1675
再見小時候
再見小時候 2020-12-06 08:16

I picked up the following piece of code from a similar question but I\'m not having any luck getting it to work.

- (void)touchesBegan:(NSSet *)touches withEv         


        
相关标签:
1条回答
  • 2020-12-06 08:37
    #import <UIKit/UIKit.h>
    
    @interface Canvas : UIImageView
    
    @property (nonatomic, assign) CGPoint location;
    
    @end
    
    
    
    
    #import "Canvas.h"
    
    @implementation Canvas
    
    - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        self.location = [touch locationInView:self];
    }
    
    - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint currentLocation = [touch locationInView:self];
    
        UIGraphicsBeginImageContext(self.frame.size);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetLineWidth(ctx, 5.0);
        CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, self.location.x, self.location.y);
        CGContextAddLineToPoint(ctx, currentLocation.x, currentLocation.y);
        CGContextStrokePath(ctx);
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        self.location = currentLocation;
    }
    
    - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint currentLocation = [touch locationInView:self];
    
        UIGraphicsBeginImageContext(self.frame.size);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetLineWidth(ctx, 5.0);
        CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, self.location.x, self.location.y);
        CGContextAddLineToPoint(ctx, currentLocation.x, currentLocation.y);
        CGContextStrokePath(ctx);
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        self.location = currentLocation;
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题