ios

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

2018-06-16  本文已影响94人  nenhall

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;

}
上一篇下一篇

猜你喜欢

热点阅读