2012-10-26 56 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

相关问题