2015-09-08 52 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 );'把這張照片剪成一圈 –