Can't get shadow on multiline nsstring

I am trying to get multi-line text to draw with a drop shadow without using the legacy APIs. It works great for one line. The relevant code looks like this:

    NSMutableParagraphStyle *paragraph =  [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;

    UIFont *f = [UIFont systemFontOfSize:20.0];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    [attributes setValuesForKeysWithDictionary:@{ NSFontAttributeName : f,
                                                  NSParagraphStyleAttributeName : paragraph,
                                                  NSForegroundColorAttributeName    : [UIColor blueColor] }];
    NSShadow * shadow = [NSShadow new];
    shadow.shadowOffset = CGSizeMake(4,4);
    shadow.shadowColor = [UIColor redColor];

   [attributes setValue:shadow forKey:NSShadowAttributeName];

    rect.origin.y = 100;
    [@"test string on one line" drawInRect:rect withAttributes:attributes];

    rect.origin.y = 150;
    [@"test string spanning more than one line" drawInRect:rect withAttributes:attributes];


and the output looks like this:

iPhone 6 showing no shadow on multiline text

I tested this on iPhone 5 (7.1.2), iPhone 6 (8.0) creating xCode 6. I also tested it on iPhone 5 when building with xCode 5.


source to share

1 answer

Some more experimentation and I found the answer is to use NSAttributedString.

Until this shows a shadow:

   NSString *s = @"test string spanning more than one line"
   [s drawInRect:rect withAttributes:attributes]


This does:

   NSAttributedString *as = [[NSAttributedString alloc] initWithString:s attributes:attributes];
   [as drawInRect:rect];


I don't think this is documented anywhere, I would like to hear it differently.



All Articles