makaron makaron - 10 months ago 47
iOS Question

text with sharp shadow around

I want to achieve the text appearance like in the pictures below:
enter image description here
enter image description here

Now I'm working on shadow around the letters and I can't figure out how to do that.

What I've tried so far:

- The solution with:

label.shadowColor = [UIColor blackColor];
label.shadowOffset = CGSizeMake(1, 2);

gives a nice sharp shadow, but it doesn't fit my needs by two reasons:

  1. It gives a shadow only from one side, set up by shadowOffset, whereas I need a "wrapping" shadow;

  2. This solution doesn't give the soft part of the shadow (gradient) as there is in the pictures;

-The solution with:

label.layer.shadowOffset = CGSizeMake(0, 0);
label.layer.shadowRadius = 5.0;
label.layer.shouldRasterize = YES;
label.layer.shadowOpacity = 1;
label.layer.shadowColor = [UIColor blackColor].CGColor;
label.layer.masksToBounds = NO;

Works great, but it gives too soft shadow even though the shadowOpacity is set to 1 and the shadowColor is set to black:

enter image description here

Obviously it's not enough and I already think about drawing in labels' context. But it is not clear to me how would I achieve the goal even through context drawing.

Any idea would be much appreciated.


Try this Create a Custom UILabel SubClass and Override the following method

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

    CGContextSetShadow(context, CGSizeMake(0.0, 0.0), 10);
    CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), 10, [UIColor blackColor].CGColor);

    [super drawTextInRect:rect];


and this bottomColorLayer to the Label

CALayer *bottomColorLayer = [CALayer layer];
bottomColorLayer.frame = CGRectMake(0, labelRect.size.height/2, labelRect.size.width, labelRect.size.height/2);
bottomColorLayer.backgroundColor = [[UIColor colorWithWhite:0 alpha:.5] CGColor];
[label.layer insertSublayer:bottomColorLayer above:(CALayer *)label.layer];

enter image description here

or If you want Gradient

CAGradientLayer *bottomGradient = [CAGradientLayer layer];
bottomGradient.frame = CGRectMake(0, labelRect.size.height/2, labelRect.size.width, labelRect.size.height/2);
bottomGradient.cornerRadius = 0.0f;
bottomGradient.colors = @[(id)[[UIColor colorWithWhite:1 alpha:.5] CGColor], (id)[[UIColor colorWithWhite:0 alpha:.5] CGColor]];
[label.layer insertSublayer:bottomGradient above:(CALayer *)label.layer];