Search code examples
ioscore-graphicsbrushstroke

iOS Brush Hardness like Photoshop


How to get the following brush smoothness(hardness) effect like photoshop?

My attempt:

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSaveGState(context);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 30);
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:0.5f].CGColor);
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 20.0f, [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f].CGColor);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGContextRestoreGState(context);

I tried adjusting alpha values, and shadow blur factor, but no successful result.

Does anybody have a solution to this? Any help would be appreciated.


Solution

  • On this image you can see following code result. I believe it is almost same to what you want.

    enter image description here

    Just outer shadow is not just enough to give that smooth effect that is why I add some inner shadow to shape with white color.

    - (void)drawRect:(CGRect)rect {
    
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // Shadows
        UIColor* shadow = UIColor.redColor;
        CGSize shadowOffset = CGSizeMake(0.1, -0.1);
        CGFloat shadowBlurRadius = 11;
        UIColor* shadow2 = UIColor.whiteColor; // Here you can adjust softness of inner shadow.
        CGSize shadow2Offset = CGSizeMake(0.1, -0.1);
        CGFloat shadow2BlurRadius = 9;
    
        // Rectangle Drawing
        UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(59, 58, 439, 52) cornerRadius: 21];
        CGContextSaveGState(context);
        CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, [shadow CGColor]);
        [UIColor.redColor setFill];
        [rectanglePath fill];
    
        // Rectangle Inner Shadow
        CGContextSaveGState(context);
        UIRectClip(rectanglePath.bounds);
        CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL);
    
        CGContextSetAlpha(context, CGColorGetAlpha([shadow2 CGColor]));
        CGContextBeginTransparencyLayer(context, NULL);
        {
            UIColor* opaqueShadow = [shadow2 colorWithAlphaComponent: 1];
            CGContextSetShadowWithColor(context, shadow2Offset, shadow2BlurRadius, [opaqueShadow CGColor]);
            CGContextSetBlendMode(context, kCGBlendModeSourceOut);
            CGContextBeginTransparencyLayer(context, NULL);
    
            [opaqueShadow setFill];
            [rectanglePath fill];
    
            CGContextEndTransparencyLayer(context);
        }
        CGContextEndTransparencyLayer(context);
        CGContextRestoreGState(context);
    
        CGContextRestoreGState(context);
    }
    

    Regarding size of the shape you have to adjust both inner and outer shadows blur radius.