1. 程式人生 > >iOS:圓形頭像和菱形頭像的實現

iOS:圓形頭像和菱形頭像的實現

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

效果圖:
這裡寫圖片描述