2015-09-08 51 views
1

我用下面的代码来掩盖UIImageView iOS中如何屏蔽WKInterfaceImage编程

#import <QuartzCore/QuartzCore.h> 

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

这里是结果:

任何一个知道如何为WKInterfaceImage做?

回答

1

您将需要使用核心图形将您的图像绘制成圆形,然后将该图像设置为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 
+0

请您用一段代码阐述,我仍然无法在代码映射我的手表套件的答案 –

+0

我将代码添加到答案 –

+1

谢谢@Stephen它的工作原理,我只需要修改调用addRoundedRectToPath(context,rect,img.size.width/2.0,img.size.height/2.0 );'把这张照片剪成一圈 –