iOS图形处理相关00『 基础知识 』iOS学习笔记

iOS给图片设置圆角

2016-08-10  本文已影响95人  YanniLiu

<h1 align = "center">iOS给图片设置圆角</h1>

通过设置layer的属性(最常用的方法)

最快速,但是影响性能,代码如下

 
 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
  imageView.backgroundColor = [UIColor redColor];
  //设置layer层的两个属性
  //设置圆角
  imageView.layer.cornerRadius = imageView.frame.size.width / 2;
  //将多余的部分切掉,这句话一定要有,不然有时候显示不出来
  imageView.layer.masksToBounds = YES;
  [self.view addSubview:imageView];

通过CAShapeLayer和贝塞尔曲线UIBezierPath画圆角图片


UIImageView *imageShape = [[UIImageView alloc]initWithFrame:CGRectMake(100, 360, 100, 100)];
    imageShape.image = [UIImage imageNamed:@"01.jpg"];
    imageShape.backgroundColor = [UIColor purpleColor];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageShape.bounds
                                                   byRoundingCorners:UIRectCornerAllCorners
                                                         cornerRadii:imageShape.bounds.size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    maskLayer.frame = imageShape.bounds;
    maskLayer.path = maskPath.CGPath;
    imageShape.layer.mask = maskLayer;
    [self.view addSubview:imageShape];

用UIBezier曲线和Core Graphics(推荐)

   UIImageView * imageBezier = [[UIImageView alloc]initWithFrame:CGRectMake(100, 220, 100, 100)];
     imageBezier.image = [UIImage imageNamed:@"01.jpg"];
    imageBezier.backgroundColor = [UIColor blueColor];
    //开始对imageView进行画图
    UIGraphicsBeginImageContextWithOptions(imageBezier.bounds.size, NO, 1.0);
    //使用贝塞尔曲线画出一个圆形图
    UIBezierPath * path =  [UIBezierPath bezierPathWithRoundedRect:imageBezier.bounds cornerRadius:imageBezier.frame.size.width] ;
    [path addClip];
    [imageBezier drawRect:imageBezier.bounds];
    
    imageBezier.image = UIGraphicsGetImageFromCurrentImageContext();
    //结束画图
    UIGraphicsEndImageContext();
    [self.view addSubview:imageBezier];


PS:这个demo我已经上传到了我的github上,有兴趣的朋友可以下载看看.

上一篇 下一篇

猜你喜欢

热点阅读