2012-10-26 60 views
4

我有一個40x40的方形圖像,我想通過剪裁進行修剪,但也在圖像周圍放置了黑色的5像素邊框。我如何掩蓋一個圓形的方形圖像,並在圖像周圍放置黑色邊框

我有被遮蔽的正方形圖像所以它現在輪

UIImage *image = self.imageView.image; 
     CGSize imageSize = image.size; 
     CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height); 

     UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); 
     // Create the clipping path and add it 
     UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect]; 
     [path addClip]; 


     [image drawInRect:imageRect]; 
     UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 

     self.imageView.image = roundedImage; 

以下但現在我還需要添加它周圍的圓形邊框。我是否需要一個新的路徑,或者我可以在上面的代碼中添加一個?

+1

[imageView.layer setBorderColor:[的UIColor blackColor ] CGColor]]; [imageView.layer setBorderWidth:1.0]; [imageView.layer setCornerRadius:10.0f];如果你像這樣設置邊界會發生什麼?它工作嗎? – iDev

+0

這段代碼將一個邊框添加到'imageView'圖層,而不是剪裁和包含的圖像。 – atxe

+0

這將工作,如果你設置imgView.clipsToBounds = YES; – Allfocus

回答

12

在代碼中添加以下三行(與任何你想要的顏色和筆觸寬度):

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]); 
[path setLineWidth:50.0f]; 
[path stroke]; 

所以就變成:

UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); 
CGContextRef ctx = UIGraphicsGetCurrentContext(); 
// Create the clipping path and add it 
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect]; 
[path addClip]; 
[image drawInRect:imageRect]; 

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]); 
[path setLineWidth:50.0f]; 
[path stroke]; 

UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

self.imageView.image = roundedImage; 
+0

完美!但將其設置爲5.0f而不是50.0f。 – jdog

相關問題