美文网首页
iOS开发中圆形图片绘制方案

iOS开发中圆形图片绘制方案

作者: 捷风 | 来源:发表于2017-10-19 09:45 被阅读9次

一般在给图片做圆形处理时,我们用得较多的可能就是 :
ImageView.layer.cornerRadius=Iv.frame.size.width *0.5 ; ImageView.layer.masksToBounds=YES;
这两行代码或许写起来比较方便、容易记起来,又或许是其他什么原因,当然少量的图片处理使用这个是完全没问题的,但是,对这里有个“但是”,但是如果你需要同时对很多图片进行圆角处理的话,建议最好不要使用这种方案,因为它对内存的消耗非常大,很容易导致页面出现卡帧的现象;
那么需要怎么避免这种情况呢,请看👇👇👇
1、在工具类中定义一个方法,在需要处理圆形图片的地方进行调用

/**
 *  imageView添加圆形图片
 *
 *  @param Iv    添加图片空间
 *  @param url   图片URL
 *  @param image 站位image
 */
+(void)imageViewCircular:(nullable UIImageView *)Iv withUrl:(nullable NSString *)url placeholderImage:(nullable NSString *)image{
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@%@",TTPROTOCOL_IMAGE_URL,url];
    [Iv sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:image ==nil ? nil :[UIImage imageNamed:image]completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        Iv.image=[image circleImage];
       
    }];
    
}

2、写一个UIImage的分类(UIImage+Category )在分类中定义一个方法【-(nullable UIImage *)circleImage 】对image进行处理

-(nullable UIImage *)circleImage{
    //NO代表透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    
    //获得上下文
    CGContextRef ctx =UIGraphicsGetCurrentContext();
    
    CGRect rect =CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctx, rect);
    
    //裁剪
    CGContextClip(ctx);
    
    //将图片画上去
    [self drawInRect:rect];
    
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

图片的圆角处理的其他的方案,欢迎补充,O(∩_∩)O谢谢!

相关文章

网友评论

      本文标题:iOS开发中圆形图片绘制方案

      本文链接:https://www.haomeiwen.com/subject/rszyuxtx.html