Search code examples
objective-ciosxcodeipadcore-graphics

Objective C: How do i smoothen the brush like a real brush?


I am building a brush app, it's almost finish and what i did was just a basic brush/drawing tool. I want to give it a more brush-like feel because in my current output it has angles and it doesn't look like a real brush ink.

here's my code:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    touchSwiped = YES;
    UITouch *touch = [touches anyObject];   
    currentTouch = [touch locationInView:self.view];
    currentTouch.y -= 20;
    UIGraphicsBeginImageContext(self.view.frame.size);
    [touchDraw.image drawInRect:CGRectMake(0, 0, touchDraw.frame.size.width, touchDraw.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 35.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), redAmt, blueAmt, greenAmt, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), endingPoint.x, endingPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentTouch.x, currentTouch.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    touchDraw.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    endingPoint = currentTouch;

    touchMoved++;

    if (touchMoved == 10) {
        touchMoved = 0;
    }
}

Solution

  • Try using the quadCurve instead of addLineToPoint.. Quad Curve make a line in a two points that don't have an angle and make your line a curve..

    CGPoint midPoint(CGPoint p1,CGPoint p2)
            {
             return CGPointMake ((p1.x + p2.x) * 0.5,(p1.y + p2.y) * 0.5);
            }
    
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event//upon moving
    
    {   
        mouseSwiped = YES;
    
        UITouch *touch = [touches anyObject];
    
        previousPoint2 = previousPoint1;
        previousPoint1 = currentTouch;
        currentTouch = [touch locationInView:self.view];
    
        CGPoint mid1 = midPoint(previousPoint2, previousPoint1); 
        CGPoint mid2 = midPoint(currentTouch, previousPoint1);
    
        // here's your ticket to the finals.. 
        CGContextMoveToPoint(context, mid1.x, mid1.y);
        CGContextAddQuadCurveToPoint(context, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);
        CGContextStrokePath(context)
    }