Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a line with a shadow, but only want to keep shadow. IOS

I am trying to draw a line with a shadow but I do not want to keep the line but only the shadow.

I have attempted to set the stroke color of the line to clear but when I do that the shadow also disappears.

The following code creates 2 lines, i only want to keep the shadow because it looks nicer and its not pixelated like the line.

Is this possible?

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0);

    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
    CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES);    

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
    CGColorRef shadowColor = CGColorCreate(colorSpace, components);
    CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(), CGSizeMake(10,10), 4.0, shadowColor);

Thanks.

like image 560
Rob Avatar asked Sep 08 '11 20:09

Rob


2 Answers

So you can't do this directly because the shadow reflects the path, so if you make the path transparent, the shadow will also be transparent. There are a few workarounds I can think of (depends on exactly what you're doing) but one sneaky way would just be to draw the shadow far enough below the path that you can just draw over it, basically erasing it. For example, if the background is white, this will accomplish what you want:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextSetLineWidth(context, 10.0);
    CGContextMoveToPoint(context, 10.0, 30.0);
    CGContextAddLineToPoint(context, 310.0, 30.0);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
    CGColorRef shadowColor = CGColorCreate(colorSpace, components);
    CGContextSetShadowWithColor(context, CGSizeMake(0.0f,20.0f), 4.0, shadowColor);
    CGContextStrokePath(context);

    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
    CGContextSetLineWidth(context, 10.0);
    CGContextMoveToPoint(context, 10.0, 30.0);
    CGContextAddLineToPoint(context, 310.0, 30.0);
    CGContextStrokePath(context);
}

hope this helps.

like image 152
pho0 Avatar answered Nov 20 '22 13:11

pho0


why dont you just draw your line as a shadow. Dont have the shadow drawn but instead draw a black line with .25 or less alpha and offset it to where you would expect the shadow to be.

like image 2
The Lazy Coder Avatar answered Nov 20 '22 14:11

The Lazy Coder