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
效果图:
相关文章推荐
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- IOS之圆形头像的实现
- iOS实现圆形头像
- iOS 实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS 圆形头像如何实现
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像 (转载,已验证可以)
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现圆形头像
- 3ff0 iOS 实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像
- iOS实现带文字的圆形头像效果
- iOS实现头像选取(照相或者图片库)、大小等比缩放、生成圆形头像 (转)
- iOS开发之Quartz 2D实现流行的圆形头像
- iOS实现圆形头像