简体   繁体   中英

WatchKit: How can I implement a text shadow?

In my Apple Watch app, I'm trying to place text over the top of an image. I've got a group with a background image and label positioned correctly. But depending on the image, my white text can sometimes be unreadable. Dark text would have the same problem or be even worse.

Is there a way to have black text just under my white text and slightly offset?

Unfortunately, the current version of WatchKit doesn't provide a way to "stack" or layer WKInterfaceLabel controls. So, the idea of including black text under the white text using a second label won't work.

You might consider rendering your drop-shadowed text as a UIImage in your Watch extension and using the image with a WKInterfaceImage control. Something like:

- (UIImage *)imageWithText:(NSString *)text shadowBlurRadius:(CGFloat)shadowBlurRadius {

    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset = CGSizeZero;
    shadow.shadowBlurRadius = shadowBlurRadius;
    shadow.shadowColor = [UIColor blackColor];

    NSDictionary *attributes = @{ NSForegroundColorAttributeName    : [UIColor whiteColor],
                                  NSFontAttributeName               : [UIFont boldSystemFontOfSize:36.0f],
                                  NSShadowAttributeName             : shadow };

    CGSize size = [text sizeWithAttributes:attributes];

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width + (2.0f * shadowBlurRadius),
                                                      size.height + (2.0f * shadowBlurRadius)),
                                           NO,
                                           2.0f);

    [text drawAtPoint:CGPointMake(shadowBlurRadius, shadowBlurRadius)
       withAttributes:attributes];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM