Tag Archives: iOS

How to draw a triangle in Apple Watch

I’ve previously covered how to draw circles and rectangles into an image when writing an Apple Watch app. I had an idea for another watch face that needed triangles – these need a different approach using Watch Kit. Basically, you have to draw a path around the perimeter of the triangle (or any other shape), then fill in the shape. Here’s a function to draw a triangle that points to the left:

    internal func drawTriangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, size : CGFloat, colour : CGColor )
    {
        context?.beginPath()
        context?.move(to: CGPoint(x: centreX - size/2.0, y: centreY))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY - size/2.0))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY + size/2.0))
        context?.closePath()
        
        context?.setFillColor(colour)
        context?.fillPath()
    }

And this is the code for drawing a rectangle:

    internal func drawRectangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, width : CGFloat, height : CGFloat, colour : CGColor )
    {
        let origin = CGPoint( x: centreX - width/2.0, y : centreY - height/2.0 )
        let rect = CGRect( origin : origin, size : CGSize(width: width, height: height) )
        
        context?.setFillColor(colour)
        context?.fill(rect)
    }

Once you can do those primitive triangle/rectangle operations, you can put them together to render any digit you like. So I used them to draw a ‘timeometer’ in this speedo watch face:

The dial is rendered as a series of ticks – at the moment, it shows minutes and hours. I have to admit I still tend to read the time from the digits at the bottom, so I may change the dial to show seconds and minutes instead.

Leave a comment

Filed under Programming, Swift

How to switch watch faces using swipe gestures

A welcome addition to WatchKit 3.0 is the swipe gesture recognizer.  Previously, I used an ordinary button to switch between modes in my Watch Face app, but now I can mimic the behaviour of official watch faces by swiping left or right.

The change is quite simple to make too. First, you just need a Group control that contains an image (into which you’ll draw the watch face). Then, you drag a couple of Swipe Gesture Recognizers into the group, and change the properties so that one is a left swipe and the other is a right swipe.

Having done that, you need to insert an action for each of the gestures – you can do that by control-dragging from the gesture in the storyboard outline into the InterfaceController code. Make sure to add an action (rather than an outlet) – that way, Xcode will create a stub method for you with the correct signature.

The logic for the swipe gesture just switches between watch faces then re-draws the time:

    // Tissot --> Hermes --> Roman
    @IBAction func swipeRight(_ sender: Any) {
        switch (watchFace.id())
        {
        case WatchFaceId.tissot: watchFace = HermesWatchFace()
        case WatchFaceId.hermes: watchFace = RomanWatchFace()
        case WatchFaceId.roman: watchFace = TissotWatchFace()
        }
        
        drawTime() // refresh with updated background & different styles
    }

and the left swipe reverses the transition order.

See also this earlier post that explains how you can draw directly into an image in WatchKit – combined with the swipe gesture recogniser, it provides a neat way to switch between different modes in any app.

Leave a comment

Filed under Swift

How to use the Digital Crown in a Watch Face App

I’ve written before that, having lived with the Apple Watch for a while, I felt the watch faces lacked variety. So, I wrote a watch face app, which I now use for the majority of the time.

For my next watch face, I thought it would be pretty cool to recreate the look of my beloved Tissot watch. One of its best features is that extra functionality is controlled by twisting/pressing the bezel. It supports date/time/stopwatch/timer – or you can hide the digital display altogether. Although WatchKit doesn’t allow you to capture a button press, you can use the digital crown to scroll between choices – so I thought I’d offer a couple of date formats as well as the option to hide the date altogether. tissot

Add a Picker control onto your storyboard and connect it to a WKInterfacePicker in your InterfaceController. There are a number of styles that you can choose, but for my purposes, I chose the default List style:
screen-shot-2017-01-12-at-19-09-55
Then it’s a matter of populating the picker’s list of items – for example, this code could go in function awake(withContext):

            let blankLine = WKPickerItem()
            blankLine.title = ""
            
            let currentDate = Date()
            let dayDateMonthLine = WKPickerItem()
            dayDateMonthLine.title = "\(currentDate.dayOfWeek()) \(currentDate.dayOfMonth()) \(currentDate.monthAsString())"
            let dateMonthYearLine = WKPickerItem()
            dateMonthYearLine.title = "\(currentDate.dayOfMonth()) \(currentDate.monthAsString()) \(currentDate.year())"
            
            InfoPicker.setHidden( false )
            InfoPicker.setItems( [ blankLine, dayDateMonthLine, dateMonthYearLine, blankLine ] )
            InfoPicker.focus()

I set the focus on the picker so that the digital crown is immediately responsive (otherwise, you’d have to select the picker first on the touch screen). I also put a blank line before and after the date formats, to make the usage more natural. The code above also uses some extension methods on Date.

Tissot style watch face

Seeing how good this looks, I think Apple are missing a trick. All of their analogue Apple Watch faces are round – I hope they ship a couple of rectangular faces in the next Watch OS upgrade.

2 Comments

Filed under Programming, Swift

How to draw text onto an image in Apple Watch App

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.

CGContextShowTextAtPoint

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 )

Screen Shot 2016-08-05 at 08.00.08

Using the same method, I updated my Watch Face App to draw the day and date onto this watch face:

Screen Shot 2016-08-07 at 21.28.23

See also: How to write a Watch Face App for Apple Watch and How to draw on top of an image in Apple WatchKit

1 Comment

Filed under Programming, Swift

How to write a Watch Face App for Apple Watch

Having owned an Apple Watch for over a year, I’ve grown a little bored with the available watch faces. So I was very impressed with the new, special edition Hermes watch face. This is quite different to any of the other faces on the Apple Watch. Unfortunately, it’s only available to new purchasers who buy the brand new Hermes Apple Watch – starting at £1000.
HermesFace2

Having written my first Watch App recently, I thought I’d have a go at writing a Watch Face App. Apple WatchKit doesn’t officially support writing watch faces, so this would have to be an ordinary App that happens to display the time. There are plenty of custom faces you can use as wall-paper to create an attractive digital watch, but I wanted the analogue look.

The approach I took was:

  • Start with an image e.g. from the custom faces library
  • Look up how to get the current time in the WatchKit API
  • Find out how to draw graphics on top of an image
  • Work out the maths to draw the hands in the right place
  • Work out how to render proper watch hands

I already blogged about how to get the current time and how to draw graphics on top of an image. So if you followed along, you can replace your Treasure Map image with a watch face image and use the createContext(), drawLine() and applyContextToImage() methods to draw the hour and minute hands. In fact, by making the colour a parameter of drawLine(), you’ve got the method to draw the second hand too.

As for the maths to draw the hands in the right place, it’s trigonometry. Both sin and cos are available in WatchKit, so convert the hours/minutes into radians and calculate the end coordinate of your watch hand, treating the length of the hand as the hypotenuse of a right-angled triangle.

[edit]I had a request to post the maths for this. Suppose you want to draw a hand at 12 minutes past. Convert that into a fraction of how far the hand has moved – here, 12 mins out of a possible 60 mins. Then work out whether it’s in the top-right, bottom-right, bottom-left or top-left quadrant of the watch face (that affects which sin/cos functions you’ll use) – here, 12/60 = 0.2, so it’s between 0.0 and 0.25, hence it’s in the first quadrant.

To calculate the x and y coordinates for the top-right quadrant, we form a right-angled triangle between the hand and the y-axis. The hand forms the hypotenuse of the triangle, let’s choose length = 100. So knowing the minutes as a fraction, and the length of the hand, here’s a function to calculate the x and y coordinates as an offset from the centre of the watch face, using trigonometry:

func handCoordinate( _ fraction : CGFloat, length : CGFloat ) -> (x : CGFloat, y : CGFloat )
{
    let x : CGFloat, y : CGFloat

    if ( 0 <= fraction && fraction < 0.25 )
    {
        let theta = CGFloat( (fraction/0.25) * π / 2.0 )
        x = length * sin( theta )
        y = -1.0 * length * cos( theta )
    }
    else
    {
        // remaining quadrants left as exercise for the reader!
    }
    
    return (x,y)
}

The simplest way of drawing the hand is then a simple drawLine() from (centreX, centreY) to (centreX + x, centreY + y). For my 42mm watch, centreX and centreY are (156,150) – other sizes will vary.
[/edit]

That leaves the trick of how to draw a proper watch hand given only the drawLine() and drawCircle() methods. This is the method I used:

WatchHand

In order to draw the white circle outline with solid black inner-circle, I used this method:

    func drawCircle( context : CGContext?, radius : CGFloat, centreX : CGFloat, centreY : CGFloat, colour : CGColor )
    {
        let diameter = radius * 2.0
        let rect = CGRect( x: centreX - radius, y : centreY - radius, width : diameter, height : diameter )
        
        CGContextSetFillColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextFillEllipseInRect( context, rect )
        
        CGContextSetLineWidth( context, 2.0 )
        CGContextSetStrokeColorWithColor( context, colour )
        CGContextStrokeEllipseInRect( context, rect )
    }

There are a couple of limitations:

That said, I’m really happy with the results:

Watch Face App

This is actually one Watch App – I changed the Image to a Button so that I could iterate through different watch faces by tapping the watch. If you do this, call button.setBackgroundImage on the button instead of image.setImage.

See also: How to draw text onto an image and How to draw on top of an image.

11 Comments

Filed under Programming, Swift

How to draw on top of an image in Apple WatchKit

Suppose you’re writing a simple game for Apple Watch – for example, you might have a treasure map image and you want to render a cross on it in a random position to locate the treasure.
treasure-map
This is tricky, because WatchKit severely limits your options for laying out UI primitives on the screen. For example, if you put a label and an image onto a StoryBoard, it will tile them (rather than letting you put one on top of the other).

The approach I’ve adopted is:

  • Create a Group in the story board and set its background image
  • Add an image view within the Group
  • Create a context and use CoreGraphics to write into it
  • Apply the context to the image view

Set up a new iOS WatchKit App, then drag a Group and Image from the Object Library onto the storyboard:
TreasureMap StoryBoard

In the WatchKit App assets, create a new image set and drag your background image onto the x2 outline:
TreasureMap ImageSet

Set the background image on the group:
TreasureMap SetBackground

Then create an outlet in the InterfaceController for the image – one way is to control-drag from the outline view of the storyboard into the interface controller’s swift file. I called mine OverlayImage to convey the purpose.

Finally, add the code that will leverage the CoreGraphics library to draw into the overlay – the work is done in drawCross() which is called from awakeWithContext(). I’ve split out line and circle drawing methods for clarity.

class InterfaceController: WKInterfaceController {
    // Create by control-dragging to the StoryBoard
    @IBOutlet var OverlayImage: WKInterfaceImage!
    
    let imageWidth : CGFloat = 312.0
    let imageHeight : CGFloat = 348.0 // 390 - 42 for status bar on 42mm watch
    
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        drawCross()
    }

    override func willActivate() { ... } // standard
    override func didDeactivate() { ... } // standard
    
    func drawCross()
    {
        // Begin image context and grab context
        let context = createContext()
        
        // Draw our primitives
        drawLine( context, startX: 75, startY: 150, endX: 125, endY: 200 )
        drawLine( context, startX: 75, startY: 200, endX: 125, endY: 150 )
        drawCircle( context, radius : 10, centreX : 100, centreY : 175 )
        
        // End by applying our graphics to the Overlay image
        applyContextToImage( context )
    }
    
    func createContext() -> CGContext?
    {
        // The 'opaque' parameter is false, so that we overlay 
        // rather than the static image underneath
        UIGraphicsBeginImageContextWithOptions( CGSizeMake( imageWidth, imageHeight ), false, 0 )
        let context = UIGraphicsGetCurrentContext()
        CGContextBeginPath( context )
        
        return context
    }
    
    func drawLine( context : CGContext?, startX : CGFloat, startY : CGFloat, endX : CGFloat, endY : CGFloat )
    {
        CGContextSetStrokeColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextSetLineWidth(context, 3.0)
        CGContextMoveToPoint( context, startX, startY )
        CGContextAddLineToPoint( context, endX, endY )
        CGContextStrokePath( context )
    }
    
    func drawCircle( context : CGContext?, radius : CGFloat, centreX : CGFloat, centreY : CGFloat )
    {
        let diameter = radius * 2.0
        let rect = CGRect( x: centreX - radius, y : centreY - radius, width : diameter, height : diameter )
        
        CGContextSetLineWidth( context, 3.0 )
        CGContextSetStrokeColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextStrokeEllipseInRect( context, rect )
    }
    
    func applyContextToImage( context : CGContext? )
    {
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        OverlayImage.setImage( img )
    }

All being well, you can now run your WatchKit App and check that the black cross and circle have been drawn on top of the background image!

TreasureMap WatchApp

3 Comments

Filed under Programming, Swift

Calculator App for Apple Watch

I was surprised that Apple didn’t include a calculator app with the Apple Watch. In the 1980’s, calculator watches were cool – having missed out then, I was keen for my Apple watch to have one.CasioCalculatorWatch

I chose to write my own calculator WatchKit App for fun, rather than purchasing one from the App Store. It’s a good choice for a first project, because the user interface is static and the focus is more on getting up the learning curve of WatchKit development. Here are some of the lessons I learnt in the process.

How to get the text from a WatchKit label
Suppose you’ve set up an outlet for a label that displays the input figures in your app – then you’d expect to be able to get the text back from it:

@IBOutlet var labelSum: WKInterfaceLabel!
//...
labelSum.setText( "42.0" )
let digits = labelSum.getText() // error - does not compile

It seems this is not supported in Xcode 7.2/Watch OS 2.1. Instead, you have to track the state in a variable and use that to populate the label.
How to store state in a WatchKit App
For a calculator App at least, you need a state machine to keep track of state, because at different stages you may be inputting the first or second number in the calculation, or re-using the previous answer in another calculation. Swift enum is a discriminated union that is well suited to this:

// Define enum type outside your interface controller
enum CalculationState
{
    case BuildingLHS( String )
    case BuildingRHS( LHS : String, Op : Operation, RHS : String ) // Waiting for Equals
    case WaitingForOperation( String ) // Got answer already, may do another operation
}

// Declare a variable to hold the state 
// as a member inside the interface controller class
class InterfaceController: WKInterfaceController {
    // ...
    var state : CalculationState
}

Use ‘RelativeToContainer’ to scale layout
When defining the UI elements on your story board, the interface controller is only approximately the size of the watch screen. My UI has all the buttons displayed at once, so it’s important to make maximum use of the screen size.
Calc - RelativeToContainer
Here, buttons 7, 8 and 9 are in a horizontal group. To fill that container, we need to use the ‘RelativeToContainer’ scaling style and fill in the proportion each UI element should take. For height, it’s 1 (i.e. the whole container), whereas for width, it’s one third (i.e. 0.33-ish). Personally, I think it would have been more obvious that this is the scaling style to choose if the proportion was displayed as a percentage, rather than a value relative to one.
How to set completion after animation
The WatchKit animation API lacks the ability to specify a completion function that runs after the initial animation changes. This is awkward if you want to flash a UI element from one colour and return to the original colour – if you run both animations in parallel, the colour doesn’t change. I used this code to add an extension method – then I could easily flash UI elements as below:

    func flashSum( origColor : UIColor, flashColor : UIColor ){
        animateWithDuration(0.25,
            animations: { () -> Void in self.labelSum.setTextColor( flashColor ) },
            completion: { () -> Void in self.labelSum.setTextColor( origColor )}
        )
    }

How to run WatchKit App on hardwareThis should be as simple as plugging the hardware into your MacBook (i.e. the iPhone that’s paired to the Apple Watch), selecting the correct device from the devices list, then running the App in the debugger. However, there are numerous pitfalls:

  • You need either a developer licence or a personal team set up. See Team | Identity in the Project settings
  • Xcode may think that the iPhone and Watch are unpaired – restarting Xcode solved this one for me, other people have had to re-boot their watch and/or phone
  • Xcode may not have the symbols for your Watch OS (this happened after I updated to Watch OS 2.1) – however, it seems happy to download them once you connect to the internet

Re-booting, re-connecting the phone to the MacBook, re-starting Xcode eventually sorted this out.
Conclusion
I’d already worked through a couple of tutorials for writing WatchKit apps, but you learn far more by writing your own.
Calc On Watch
The end result looks great, although the buttons are slightly too small for frequent use, even on a 42mm Apple Watch.

1 Comment

Filed under Programming, Swift

Keyboard handling in Swift for iOS App

swiftI’ve updated my hobby project to take keyboard input. This ought to be pretty simple, but I came across a few snags that stopped the user experience being as smooth as should be.

Simulator only presents the pop-up keyboard once

This has been bothering me for a while, I resorted to switching to a different simulator profile (e.g. iPhone 4s / iPhone 5). It turns out that, by typing into the laptop keyboard instead of tapping the UI keyboard, the switch to hardware keyboard was semi-permanent. As per this StackOverflow page, you can restore the keyboard by in the Similar by Hardware -> Keyboard -> Toggle Software Keyboard (or ⌘K).

How to change the pop-up keyboard to ‘Done’

By default, the pop-up keyboard shows the enter/return key as “Return”. For some instances, you want to change that – this is as simple as changing the “Return Key” property on the text field in the story board:
ReturnKeyAppearance

How to dismiss keyboard when user presses return key

By default, the software keyboard does not disappear when you tap return (either on the hardware keyboard or on the software keyboard). There are several steps to achieve this, which are well discussed on StackOverflow. There are a couple of implementations choices for textFieldShouldReturn, this one worked for me:

    // UITextFieldDelegate implementation
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }

coupled with the change below for leaving the text field.

How to dismiss keyboard when user leaves the text field

Another obvious feature I wanted is to dismiss the keyboard if the user taps elsewhere in the App. The key here is to tell the view to recognise a tap (that is, UITapGestureRecognizer). See ‘Close iOS keyboard by touching anywhere’ on StackOverflow discussion.

Leave a comment

Filed under Programming, Swift

How to upload iOS App onto iPhone

XcodeI’ve been working on a hobby project for a while, learning Swift and gaining some experience of iOS App development. I reached the stage where the app was worth testing on my iPhone, but found that my version of Xcode (an early v7 beta) required an Apple Developer Licence!

Fortunately, it turns out that upgrading to Xcode 7.2 meant that I could upload to my own phone simply by providing my Apple ID. The upgrade was much easier than I had expected, compared to the number of bad reports on the internet. I used the App Store to upgrade, maybe it’s harder if you download and install the application directly.

Next, I had to find out how to install an application on my device from Xcode. First, connect the device to the Macbook and it will appear in the device list in Xcode above the simulated devices (i.e. all the iPhone and iPad models). Selecting the device by name and clicking run kicks off a full install and runs the app on the phone.

The final question was how to configure my phone to allow apps written by me to run – this was answered on the Apple Developer Forum, and is simply a matter of becoming familiar with Settings -> General -> Profile / Developer App.

I’m impressed by how well Xcode has automated this process, I’m sure a lot of work has gone into making installation onto a device a positive developer experience.

Leave a comment

Filed under Programming, Swift

Tutorial: Writing your first iOS App

I’ve finished working through this excellent introduction to writing iOS apps. Having written step-by-step guides for developers learning new software myself, it’s clear just how much work has gone into this guide to make it accurate as well as useful and informative.

  • Having never used Xcode before, the guide did a good job of introducing the development environment and showing the workflow and how to manipulate the various views
  • The FoodTracker application itself covers quite a few techniques – it’s a shame that some of the early lessons are later deleted as the app is built, but it’s a trade-off to get something to run quickly
  • The frameworks clearly do much of the heavy-lifting. This reminds me of writing user interfaces in versions of Visual Basic – you didn’t need to know much of VB as a language, it was more about leveraging the tools to get a result
  • Swift is very concise, parameter syntax takes some getting used to (some parameters have both external and internal names, which is esoteric) but even the passing parameters by name is starting to grow on me.
  • It’s very cool that unit testing is integrated in the dev tools – I’m sure I’ll be writing plenty of tests against my data model when I work on this for real.

I have a couple of ideas for apps that I’d like to write for my new Apple Watch, so next I’m looking to try a tutorial specifically for a Watch app.

Leave a comment

Filed under Programming, Swift