3

I'm trying to get multiline text to draw with a drop shadow without using deprecated APIs. It works fine for a single line. The relevant code looks like this:

-(void)drawRect:(CGRect)rect
{
    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 have tested this on iPhone 5 (7.1.2), iPhone 6 (8.0), building with xCode 6. I have also tested it on the iPhone 5 when building with xCode 5.

Airsource Ltd
  • 32,379
  • 13
  • 71
  • 75

1 Answers1

6

Some more experimentation, and I discovered that the answer is to use an NSAttributedString.

While this does not show 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, would love to hear otherwise.

Airsource Ltd
  • 32,379
  • 13
  • 71
  • 75
  • One should think that 16 years after the inital release of OS X they should have gotten round to write up a decent documentation of NSAttributedString and its attributes. Nope. BTW, you saved me a lot of hassle with that one. – Joe Völker Sep 10 '16 at 19:56