iOS 实现图片圆角的几种方式

第一种方法:通过设置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];

第二种方法:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"1"];
    //开始对imageView进行画图
    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];

第三种方法:使用CAShapeLayer和UIBezierPath设置圆角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"1"];
    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;
    imageView.layer.mask = maskLayer;
    [self.view addSubview:imageView];

以上三种方法来自简书链接 http://www.jianshu.com/p/e97348f42276
这个链接的文章里说第三种方法最好 对内存消耗最少,可是在另一篇比较权威的文章http://www.jianshu.com/p/57e2ec17585b《iOS-离屏渲染详解》里说第三种方法会使用到mask属性,会离屏渲染,不仅这样,还曾加了一个 CAShapLayer对象.着实不可以取。并指出第二种方法比较可取。另外还提出了第四种方法。
第四种方法:使用带圆形的透明图片.(需要UI做一个切图)

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"美国1.jpeg"];
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView1.image = [UIImage imageNamed:@"圆形白边中空图"];
    [self.view addSubview:imageView];
    [self.view addSubview:imageView1];

扫描二维码关注公众号,回复: 4036150 查看本文章

最好最好的方法应该是第四种了,虽然比较笨, 但是不会引发离屏渲染,对内存消耗会比较小。

猜你喜欢

转载自blog.csdn.net/a18339063397/article/details/82911300