您的位置:首页 > 移动开发 > IOS开发

iOS:圆形头像和菱形头像的实现

2017-03-09 18:19 323 查看

1.圆形头像

为UIImage添加一个分类UIImage+Clip.

#import "UIImage+Clip.h"

@implementation UIImage (Clip)

//第一个参数是图片名称 第二个参数是边框宽度
+ (instancetype)clipImageWithImageName:(NSString *)name border:(CGFloat)border {
UIImage *img = [UIImage imageNamed:name];
//开启绘图上下文
UIGraphicsBeginImageContext(img.size);
CGPoint center = CGPointMake(img.size.width * 0.5, img.size.height * 0.5);
CGFloat radius = MIN(center.x, center.y);
//先画一个白色的圆
UIBezierPath *bgPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
[[UIColor whiteColor] setFill];
[bgPath fill];

//再画一个小一点的圆
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius - border startAngle:0 endAngle:M_PI * 2 clockwise:YES];
//设置剪裁区域
[path addClip];
[img drawAtPoint:CGPointZero];

UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImg;
}

@end


在控制器中使用

#import "ViewController.h"
#import "UIImage+Clip.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
self.imageView.image = [UIImage clipImageWithImageName:@"a" border:10];
}

@end


效果图:



2.菱形头像

首先也是为UIImage添加一个分类UIImage+Clip.

#import "UIImage+Clip.h"

@implementation UIImage (Clip)

+ (instancetype)clipImgWithName:(NSString *)name {
UIImage *img = [UIImage imageNamed:name];
//开启绘图上下文
UIGraphicsBeginImageContext(img.size);
//M_SQRT2是根号2
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, img.size.width * 0.5 * M_SQRT2, img.size.height * 0.5 * M_SQRT2) cornerRadius:50];
//矩阵操作
[path applyTransform:CGAffineTransformMakeRotation(M_PI_4)];
[path applyTransform:CGAffineTransformMakeTranslation(img.size.width * 0.5, 0)];
//设置剪裁区域
[path addClip];
[img drawAtPoint:CGPointZero];

UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImg;
}

@end


在控制器中使用:

#import "ViewController.h"
#import "UIImage+Clip.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.imageView.backgroundColor = [UIColor yellowColor];
self.imageView.image = [UIImage clipImgWithName:@"a"];
}

@end


效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: