我以前使用以下代码来屏蔽iOS中的UIImageView
#import <QuartzCore/QuartzCore.h>
profilePhoto.layer.masksToBounds = YES;
profilePhoto.layer.cornerRadius = profilePhoto.bounds.size.width/2;
以下是结果:
任何人都知道如何为WKInterfaceImage
做同样的事情吗?
答案 0 :(得分:1)
您需要使用Core Graphics将图像蒙版绘制为圆形,然后将该图像设置为WKInterfaceImage。有关如何使用Core Graphics绘制带圆形图的图像,请参阅此文章。 How to mask a square image into an image with round corners in the iPhone SDK?
以下是从其他SO帖子中复制的代码,并稍作修改以将图像剪切为圆圈。 (我没有运行此代码,因此可能存在一些问题。它应该让你接近。)
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