ios Image裁剪成圓形的方法

theFeng-發表於2014-10-17

我知道的實現方法有三種。
1、通過image mask來操作,需要新增mask目標圖片。

2、通過imageview的layer來操作
如下程式碼

  1. UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"oiuyfdsa.png"]];  
  2.    imageView.frame = CGRectMake(20.f, 20.f, 100.f, 100.f);  
  3.    imageView.layer.masksToBounds = YES;  
  4.    imageView.layer.cornerRadius = 50;  

a.這種方法需要新增QuarztCore框架才能操作
b.cornerradus的確定問題

3、能過程式碼對畫布裁剪成圓形–》然後再將原始影象畫出來–》

  1. -(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {  
  2.     UIGraphicsBeginImageContext(image.size);  
  3.     CGContextRef context = UIGraphicsGetCurrentContext();  
  4.     CGContextSetLineWidth(context, 2);  
  5.     CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);  
  6.     CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);  
  7.     CGContextAddEllipseInRect(context, rect);  
  8.     CGContextClip(context);  
  9.       
  10.     [image drawInRect:rect];  
  11.     CGContextAddEllipseInRect(context, rect);  
  12.     CGContextStrokePath(context);  
  13.     UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();  
  14.     UIGraphicsEndImageContext();  
  15.     return newimg;  
  16. }  

上面程式碼注意 如果裁剪後沒有使用 CGContextAddEllipseInRect(context, rect);
CGContextStrokePath(context); 這條程式碼 就會引起背景為白色時看不出來任務效果。
這裡是橢圓操作

相關文章