Thursday, March 19, 2015

How to use NSShadow


As Apple iOS Documents mentions:

An NSShadow object may be used in one of two ways. First, it may be set, like a color or a font, in which case its attributes are applied to all content drawn thereafter—or at least until another shadow is applied or a previous graphics state is restored. Second, it may be used as the value for the NSShadowAttributeName text attribute, in which case it is applied to the glyphs corresponding to the characters bearing this attribute.

Thus, There TWO ways to implement NSShadow to your code.

1st, NSShadow could be set as attributes to all content drawn thereafter.

image
////  ShadowedRectangle.m//  NSShadowDemo////  Created by Antonio081014 on 3/18/15.//  Copyright (c) 2015 Antonio081014.com. All rights reserved.//

#import "ShadowedRectangle.h"

@implementation ShadowedRectangle

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    UIFont *font = [UIFont boldSystemFontOfSize:30.f];
    
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor redColor];
    shadow.shadowBlurRadius = 0.0;
    shadow.shadowOffset = CGSizeMake(0.0, 2.0);
    
    NSDictionary *attributes = @{NSShadowAttributeName          : shadow,
                                 NSForegroundColorAttributeName : [UIColor yellowColor],
                                 NSFontAttributeName            : font,
                                 NSBackgroundColorAttributeName : [UIColor greenColor]};
    
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:@"Text has shadows" attributes:attributes];
    
    [attributedText drawInRect:rect];
}

@end

2nd, NSShadow could be used as the value for the NSShadowAttributeName text attribute.

// Customize the UINavigationBar Title Font.
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
                                                       shadow, NSShadowAttributeName,
                                                       [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName,
                                                       nil]];

While, as seen on above examples, NSShadow could be easily applied to the Text as attributes, it could be also applied to images(pixels). Example could be found here.

If you want to read more, please check out http://www.antonio081014.com.

No comments :

Post a Comment