IOS启程06—iOS设置圆角图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl18603543572/article/details/77999773

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层

猜你喜欢

转载自blog.csdn.net/zl18603543572/article/details/77999773