5

I want to apply inner-shadow to a UILabel. I have a solution, but it's not good enough. Anyone with a better solution?

// UILabel subclass

- (void) drawTextInRect:(CGRect)rect {
    CGSize myShadowOffset = CGSizeMake(0, 2);
    float myColorValues[] = {255, 0, 0, 1};

    CGContextRef myContext = UIGraphicsGetCurrentContext();
    CGContextSaveGState(myContext);

    CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef myColor = CGColorCreate(myColorSpace, myColorValues);

    CGContextSetShadowWithColor (myContext, myShadowOffset, 5, myColor);
    CGContextSetBlendMode(myContext, kCGBlendModeLighten);

    [super drawTextInRect:rect];

    CGColorRelease(myColor);
    CGColorSpaceRelease(myColorSpace); 

    CGContextRestoreGState(myContext);
}

I'm familiar with the layer property of UILabel, but shadow offset gives us a outer-shadow, NOT inner-shadow (unless i'm missing something).

Jasarien
  • 58,279
  • 31
  • 157
  • 188
Mustafa
  • 20,504
  • 42
  • 146
  • 209

3 Answers3

24

Borrowing on Ruben's answer above, if you do the reverse ie. set your text color equal to your background color (with low alpha) and then set the shadow to be a stronger color, it creates a decent inset effect. Here's what I mean (Note: My view background is white):

cell.textLabel.textColor     = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
cell.textLabel.shadowColor   = [UIColor darkGrayColor];
cell.textLabel.shadowOffset  = CGSizeMake(-1.0,-1.0);
[cell.textLabel setText:@"Welcome to MyApp!"];

and this is the output

inset UILabel text

This would probably only work on very light backgrounds as I suspect it will create unwanted overlay on darker backgrounds.

You can ofcourse vary the shadowOffset to change the direction of light.

Nav
  • 1,185
  • 16
  • 23
4

I tried to do this but finally opted to use the default shadowOffset and play with the shadowColor to give the inner drop shadow effect to the text. In small texts it gives you a good inner shadow effect. For example, if you have a grayColor background and apply a whiteColor to the shadow, then you have an acceptable inner shadow effect.

Sometimes, it's better to design those texts with graphic tools and make localized copies if needed.

Ruben Marin
  • 1,639
  • 14
  • 24
3

Answer here : Inner Shadow in UILabel Long code but it seems to work

Community
  • 1
  • 1
CedricSoubrie
  • 6,657
  • 2
  • 39
  • 44