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



转载于:https://www.cnblogs.com/soulDn/p/10177708.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值