iOS 画圆图片的几种方法

方法一:

self.cycleImv= [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 50, 50)];

[self.view addSubview:self.cycleImv];

// 为图片切圆

self.cycleImv.layer.masksToBounds = YES;

self.cycleImv.layer.cornerRadius = self.cycleImv.frame.size.width / 2.0;

// 为图片添加边框,根据需要设置边框

self.cycleImv.layer.borderWidth = 2.0;//边框的宽度

self.cycleImv.layer.borderColor = [UIColor redColor].CGColor;//边框的颜色

方法二:

- (void)drawRect:(CGRect)rect

{

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.cycleImv.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:self.cycleImv.bounds.size];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

//设置大小

maskLayer.frame = self.cycleImv.bounds;

//设置图形样子

maskLayer.path = maskPath.CGPath;

self.cycleImv.layer.mask = maskLayer;

}

方法三:

将网络图片裁剪为圆形,首先建立一个UIImage分类UIImage+Extension,一个UIImageView分类UIImageView+CircularImv。

UIImage+Extension.h文件

#import@interface UIImage (Extension)

- (UIImage *)circleImage;

@end

UIImage+Extension.m文件

#import "UIImage+Extension.h"

@implementation UIImage (Extension)

- (UIImage *)circleImage

{

// 开始图形上下文,NO代表透明

UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);

// 获得图形上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

// 设置一个范围

CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

// 根据一个rect创建一个椭圆

CGContextAddEllipseInRect(ctx, rect);

// 裁剪

CGContextClip(ctx);

// 将原照片画到图形上下文

[self drawInRect:rect];

// 从上下文上获取剪裁后的照片

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

// 关闭上下文

UIGraphicsEndImageContext();

return newImage;

}

@end

 

使用了SDWebImage加载网络图片,所以加上UIImageView+WebCache.h头文件。

UIImageView+CircularImv.h文件

#import@interface UIImageView (CircularImv)

- (void)setCircularImvURL:(NSString *)imageUrl holderImageName:(NSString *)imageName;

@end

UIImageView+CircularImv.m文件

#import "UIImageView+CircularImv.h"

#import "UIImageView+WebCache.h"

#import "UIImage+Extension.h"

@implementation UIImageView (CircularImv)

- (void)setCircularImvURL:(NSString *)imageUrl holderImageName:(NSString *)imageName

{

//占位图片,当URL上下载的图片为空,就显示该图片

UIImage *placeholder = [[UIImage imageNamed:imageName] circleImage];

[self sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

//当图片下载完会来到这个block,执行以下代码

self.image = image ? [image circleImage] : placeholder;

}];

}

@end



posted @ 2018-12-26 10:13  SoulDu  阅读(1253)  评论(0编辑  收藏  举报