iOS UIImage剪切圆形

 

//.h文件

#import <UIKit/UIKit.h>

 

@interface UIImage (XG)

/**

 *  @param icon         头像图片名称

 *  @param borderImage  边框的图片名称

 *  @param border       边框大小

 *

 *  @return 圆形的头像图片

 */

+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border;

@end

 

//.m文件

#import "UIImage+XG.h"

 

@implementation UIImage (XG)

+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border{

    //头像图片

    UIImage * image = [UIImage imageNamed:icon];

    //边框图片

    UIImage * borderImg = [UIImage imageNamed:borderImage];

    //

    CGSize size = CGSizeMake(image.size.width + border, image.size.height + border);

    

    //创建图片上下文

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);

    

    //绘制边框的圆

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextAddEllipseInRect(context, CGRectMake(0, 0, size.width, size.height));

    

    //剪切可视范围

    CGContextClip(context);

    

    //绘制边框图片

    [borderImg drawInRect:CGRectMake(0, 0, size.width, size.height)];

    

    //设置头像frame

    CGFloat iconX = border / 2;

    CGFloat iconY = border / 2;

    CGFloat iconW = image.size.width;

    CGFloat iconH = image.size.height;

    

    //绘制圆形头像范围

    CGContextAddEllipseInRect(context, CGRectMake(iconX, iconY, iconW, iconH));

    

    //剪切可视范围

    CGContextClip(context);

    

    //绘制头像

    [image drawInRect:CGRectMake(iconX, iconY, iconW, iconH)];

    

    //取出整个图片上下文的图片

    UIImage *iconImage = UIGraphicsGetImageFromCurrentImageContext();

    

    return iconImage;

}

@end

  borderImage 是边框  不需要的话给nil就可以

  border   是边框宽度 不需要的话给0就行了

UIImage * image = [UIImage imageWithIconName:@"头像.png" borderImage:nil border:0];

 

转载于:https://www.cnblogs.com/guochaoboke/p/4740243.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值