1. 程式人生 > >IOS啟程06—iOS設定圓角圖片

IOS啟程06—iOS設定圓角圖片

iOS設定圓角的三種方式


1 方法一 通過設定layer的屬性

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//只需要設定layer層的兩個屬性
//設定圓角
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
//將多餘的部分切掉
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];

2 方法二 使用貝塞爾曲線UIBezierPath和Core Graphics框架畫出一個圓角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"img"];
    //建立點陣圖
    //引數二 NO 表示圖形不使用透明
    //引數三 影象縮放比例為1.0
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
    //使用貝塞爾曲線畫出一個圓形圖
    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:imageView.frame.size.width] addClip]; [imageView drawRect:imageView.bounds]; //從上下文中獲取圖片 imageView.image = UIGraphicsGetImageFromCurrentImageContext(); //結束畫圖 關閉圖形上下文 UIGraphicsEndImageContext(); [self.view addSubview:imageView];
2.1 UIGraphicsBeginImageContextWithOptions函式解析
函式原型為:
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
size——引數size為新建立的點陣圖上下文的大小。它同時是由UIGraphicsGetImageFromCurrentImageContext函式返回的圖形大小
opaque—透明開關,如果圖形完全不用透明,設定為YES以優化點陣圖的儲存。
scale—–縮放因子 iPhone 42.0,其他是1.0。雖然這裡可以用[UIScreen mainScreen].scale來獲取,但實際上設為0後,系統就會自動設定正確的比例了。


UIGraphicsBeginImageContext
建立一個基於點陣圖的上下文(context),並將其設定為當前上下文(context)。方法宣告如下:
void UIGraphicsBeginImageContext(CGSize size);
引數size為新建立的點陣圖上下文的大小。它同時是由UIGraphicsGetImageFromCurrentImageContext函式返回的圖形大小。
該函式的功能同UIGraphicsBeginImageContextWithOptions的功能相同,相當與UIGraphicsBeginImageContextWithOptions的opaque引數為NO,scale因子為1.0

3 方法三 使用CAShapeLayer和UIBezierPath設定圓角

需要匯入

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"img"];

//定義繪製曲線路徑
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];

//初始化
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
//設定大小
maskLayer.frame = imageView.bounds;
//設定繪製圖形曲線
maskLayer.path = maskPath.CGPath;
//設定layer mask
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];

在每一View的layer層中有一個mask屬性,他就是專門來設定該View的遮罩效果的。該mask本身也是一個layer層