Mahmoud Adam
Mahmoud Adam

Reputation: 5852

How to mask WKInterfaceImage programmatically

I used to use the following code to mask UIImageView in iOS

#import <QuartzCore/QuartzCore.h>

profilePhoto.layer.masksToBounds = YES;
profilePhoto.layer.cornerRadius = profilePhoto.bounds.size.width/2;

and here is the result:

Any one know how to do the same for WKInterfaceImage?

Upvotes: 1

Views: 241

Answers (1)

Stephen Johnson
Stephen Johnson

Reputation: 5121

You will need to use Core Graphics to draw your image masked to a circle and then set that image to WKInterfaceImage. See this post for how to draw an image with a circle map using Core Graphics. How to mask a square image into an image with round corners in the iPhone SDK?

Here is the code copied from the other SO post and modified just a little to get the image clipped to a circle out. (I haven't run this code, so there may be a few issues with it. It should get you close.)

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

UIImage* img = <My_Image_To_Draw?
UIGraphicsBeginImageContextWithOptions(img.size, NO, 2.0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGRect rect = CGRectMake(0,0,img.size.width, img.size.height);
addRoundedRectToPath(context, rect, img.size.width, img.size.height);
CGContextClip(context);
[image drawInRect:rect];
UIImage* imageClippedToCircle = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);

//Now you can use imageClippedToCircle

Upvotes: 1

Related Questions