详解iOS 裁剪圆形图像并显示(类似于微信头像)

2020-01-20 23:27:38于丽

iOS,裁剪圆形头像,裁剪头像

在弹出的如图3所示的对话框中,“File”写入类别的名称(本例中是DY),“File Type”选择Category,“Class”选择UIImage。然后点击“Next”按钮,将新文件保存。

iOS,裁剪圆形头像,裁剪头像

3. 编写类别中的代码

UIImage+DY.h文件中


#import <UIKit/UIKit.h>

@interface UIImage (DY)

+ (instancetype)circleOldImage:(UIImage *)originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;

@end

UIImage+DY.m文件中


#import "UIImage+DY.h"

@implementation UIImage (DY)

+ (instancetype)circleOldImage:(UIImage *)originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
  // 1.加载原图
  UIImage *oldImage = originalImage;

  // 2.开启上下文
  CGFloat imageW = oldImage.size.width + 2 * borderWidth;
  CGFloat imageH = oldImage.size.height + 2 * borderWidth;
  CGSize imageSize = CGSizeMake(imageW, imageH);
  UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);

  // 3.取得当前的上下文
  CGContextRef ctx = UIGraphicsGetCurrentContext();

  // 4.画边框(大圆)
  [borderColor set];
  CGFloat bigRadius = imageW * 0.5; // 大圆半径
  CGFloat centerX = bigRadius; // 圆心
  CGFloat centerY = bigRadius;
  CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
  CGContextFillPath(ctx); // 画圆

  // 5.小圆
  CGFloat smallRadius = bigRadius - borderWidth;
  CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
  // 裁剪(后面画的东西才会受裁剪的影响)
  CGContextClip(ctx);

  // 6.画图
  [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];

  // 7.取图
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

  // 8.结束上下文
  UIGraphicsEndImageContext();

  return newImage;
}


@end

+(instancetype)circleOldImage:(UIImage )originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor )borderColor方法的说明:

    这是一个类方法,最终返回的是一个UIImage的类; 方法中originalImage参数指的是从照片库或者拍照后选中的照片(可能是经过系统裁剪的); 方法中borderWidth参数指的是最终显示的圆形图像的边框的宽度,可以可以根据自己的需要设置宽度; 方法中的borderColor参数指的是最终显示的圆形图像的边框的颜色,可以可以根据自己的需要设置颜色。

4. 实现裁剪成圆形图像并显示

ViewController.h文件


#import <UIKit/UIKit.h>
#import "UIImage+DY.h" //加载类别

@interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate> //一定要添加这两个Delegate


@property (strong, nonatomic) UIImagePickerController *imagePickerController;

- (IBAction)btnPressed:(id)sender;

@property (strong, nonatomic) IBOutlet UIImageView *ablumImageView;


@end