Search code examples
xcodeimageviewwatchkitapple-watch

How to round WKInterfaceImage's corners in an  Watch app?


There're lot of  Watch apps which has rounded corners for their WKInterfaceImages. I'm trying to round even some WKInterfaceImages in my test app but I can't understand how to do that.

I can't work with imageView.layer. ... as with normal iPhone apps and I can't find an alternative to do that using code or storyboard.

Do I have to mask all PNGs or there's a simpler way?


Solution

  • You are right CALayer and UIView are not directly available on watchOS 2. But you are able to use graphic functions and for instance this approach is perfectly acceptable on Watch.

    The analogue in Swift:

    class ImageTools {
        class func imageWithRoundedCornerSize(cornerRadius:CGFloat, usingImage original: UIImage) -> UIImage {
            let frame = CGRectMake(0, 0, original.size.width, original.size.height)
    
            // Begin a new image that will be the new image with the rounded corners
            UIGraphicsBeginImageContextWithOptions(original.size, false, 1.0)
    
            // Add a clip before drawing anything, in the shape of an rounded rect
            UIBezierPath(roundedRect: frame, cornerRadius: cornerRadius).addClip()
    
            // Draw the new image
            original.drawInRect(frame)
    
            // Get the new image
            let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
    
            // Lets forget about that we were drawing
            UIGraphicsEndImageContext()
    
            return roundedImage
        }
    }
    

    Somewhere in your WKInterfaceController class:

    let originalImage = UIImage(named: "original-image")!
    let roundedImage = ImageTools.imageWithRoundedCornerSize(60, usingImage: originalImage)
    
    // Set `UIImage` for your `WKInterfaceImage`
    imageOutlet.setImage(roundedImage)