如何以编程方式屏蔽 WKInterfaceImage

How to mask WKInterfaceImage programmatically

我曾经使用下面的代码在iOS

中屏蔽UIImageView
#import <QuartzCore/QuartzCore.h>

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

结果如下:

有人知道如何为 WKInterfaceImage 做同样的事情吗?

您将需要使用 Core Graphics 将您的图像绘制成一个圆圈,然后将该图像设置为 WKInterfaceImage。请参阅此 post,了解如何使用 Core Graphics 绘制带有圆形贴图的图像。 How to mask a square image into an image with round corners in the iPhone SDK?

这是从另一个 SO post 复制的代码,并稍作修改以将图像剪裁成一个圆圈。 (我没有运行这个代码,所以它可能有一些问题。它应该能让你接近。)

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