IOS中设置圆角图片

##iOS设置圆角的三种方式框架

<hr/>函数

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 4是2.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设置圆角

须要导入<AVFoundation/AVFoundation.h>优化

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层code

相关文章
相关标签/搜索