Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply inner-shadow to UILabel [duplicate]

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).

like image 833
Mustafa Avatar asked Apr 28 '11 10:04

Mustafa


3 Answers

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.

like image 120
Nav Avatar answered Nov 19 '22 12:11

Nav


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.

like image 29
Ruben Marin Avatar answered Nov 19 '22 14:11

Ruben Marin


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

like image 3
CedricSoubrie Avatar answered Nov 19 '22 13:11

CedricSoubrie