关于图片圆角的优化

2017-05-23  本文已影响0人  able_

平常我们使用的圆角都是使用:

    _imgIcon=[[UIImageView alloc] initWithFrame:CGRectMake(KScreenWidth-20-10-43, 18, 42, 42)];
    _imgIcon.layer.cornerRadius=21.0;
//    _imgIcon.image=[UIImage imageNamed:@"默认头像"];
    _imgIcon.clipsToBounds=YES;
    [btnIcon addSubview:_imgIcon];

过多的使用可能会造成GPU性能的损耗。

于是我继续查资料,发现图片的圆角可以将图片进行进行重绘,得到一张新的图片。方法如下:borderW这个主要设置头像的边框宽度


-(UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{
    //0.加载图片
//    UIImage *image=[UIImage imageNamed:@"阿狸头像"];
    //1.确定边框宽度
//    CGFloat borderW=10;
    //2.开启一个上下文
    CGSize size =CGSizeMake(image.size.width + 2*borderW, image.size.height + 2*borderW);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    //3.绘制大圆。显示出来
    UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [borderColor set];
    [path fill];        
    //4.绘制一个小圆,显示出来
    UIBezierPath *clipPath=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
    [clipPath addClip];
    //5.把图片绘制到上下文当中
    [image drawAtPoint:CGPointMake(borderW, borderW)];
    //6.从上下文当中取出图片
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    //7.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

然后调用的时候:

    self.imageV.image=[UIImage imageWithBorder:10.0 color:[UIColor greenColor] image:[UIImage imageNamed:@"阿狸头像"]];
WechatIMG1.jpeg
上一篇 下一篇

猜你喜欢

热点阅读