Suppose you want to label an item in your WatchKit App. If you’re able to put a label widget onto the storyboard next to the item, that’s fine – but if you’re using Core Graphics to construct an overlay image, chances are you’ll need to draw the text onto the image too. My ultimate aim was to be able to draw the date on my Watch Face App.
It took some digging to find out how to do this. The obvious candidate was CoreGraphics.CGContextShowTextAtPoint, but that’s deprecated from WatchKit 2.0 onwards. Its replacement is the CoreText library, but “import CoreText” doesn’t find it.
Searching on StackOverflow met with little success, possibly because people’s solutions might work for iPhone Apps but don’t satisfy the restricted API available for WatchKit Apps. However, I found this gem which did work on the Apple Watch.
As a worked example, let’s take the Treasure Map App from an earlier post. It’s natural for a treasure map to indicate what’s buried at the cross. I’ve changed the method signature from the one on StackOverflow so that you specify the centre of the text block.
func drawText( context : CGContext?, text : NSString, centreX : CGFloat, centreY : CGFloat ) { let attributes = [ NSFontAttributeName : UIFont.systemFontOfSize( 20 ), NSForegroundColorAttributeName : UIColor.blackColor() ] let textSize = text.sizeWithAttributes( attributes ) text.drawInRect( CGRectMake( centreX - textSize.width / 2.0, centreY - textSize.height / 2.0, textSize.width, textSize.height ), withAttributes : attributes ) }
Calling this from drawCross() in the Treasure Map App results in a neat label underneath the cross:
drawText( context, text: "Gold", centreX: 100, centreY: 210 )
Using the same method, I updated my Watch Face App to draw the day and date onto this watch face:
See also: How to write a Watch Face App for Apple Watch and How to draw on top of an image in Apple WatchKit
Pingback: How to write a Watch Face App for Apple Watch | musingstudio