美文网首页ios
iOS通过按压的力度来控制线条的粗细

iOS通过按压的力度来控制线条的粗细

作者: nenhall | 来源:发表于2018-06-16 16:21 被阅读94次

    iOS通过按压的力度来控制线条的粗细

    @interface ViewController ()
    {
        CGPoint touchPoint;
        UIImageView *canDraw;
    }
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        canDraw = [[UIImageView alloc] initWithFrame:self.view.bounds];
        canDraw.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:canDraw];
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [touches anyObject];
        touchPoint = [touch locationInView:canDraw];
    }
    
    - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [touches anyObject];
        CGPoint currentPoint = [touch locationInView:canDraw];
    
        UIGraphicsBeginImageContext(canDraw.frame.size);
        [canDraw.image drawInRect:CGRectMake(0.0, 0.0, canDraw.frame.size.width, canDraw.frame.size.height)];
    
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    
        float lineWidthc = 10.0;
        if ([touch respondsToSelector:@selector(force)]) {
            NSLog(@"force:%f", touch.force);
            lineWidthc = lineWidthc * touch.force;
        }
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), lineWidthc);
    
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), touchPoint.x, touchPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        canDraw.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        touchPoint = currentPoint;
    
    }
    

    相关文章

      网友评论

        本文标题:iOS通过按压的力度来控制线条的粗细

        本文链接:https://www.haomeiwen.com/subject/ftybeftx.html