绘制图片

typedef NS_ENUM(NSInteger,DWContentMode)//图片填充模式
{
    DWContentModeScaleAspectFit,//适应模式
    DWContentModeScaleAspectFill,//填充模式
    DWContentModeScaleToFill//拉伸模式
};
复制代码
///获取带圆角的图片
/*
 radius:返回图片的圆角半径
 圆角半径不可超过图片尺寸的1/2,否则按1/2处理
 
 width:返回图片的宽度
 返回的图片为一个宽高相等的矩形区域,但图片且居中显示
 
 mode:返回图片的填充模式
 适应模式:以原图片比例,能显示全部图片的最大尺寸进行填充
 填充模式:以原图片比例,图片能充满容器的最小尺寸进行填充
 拉伸模式:以拉伸图片能够使图片充满容器的尺寸进行填充
 */

-(UIImage *)dw_CornerRadius:(CGFloat)radius withWidth:(CGFloat)width contentMode:(DWContentMode)mode
{
    CGFloat originScale = self.size.width / self.size.height;
    CGFloat height = width / originScale;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat maxV = MAX(width, height);
    if (radius < 0) {
        radius = 0;
    }
    UIImage * image = nil;
    CGRect imageFrame;
    if (mode == DWContentModeScaleAspectFit) {//根据图片填充模式制定绘制frame
        if (originScale > 1) {//适应模式
            imageFrame = CGRectMake(0, (width - height) / 2, width,height);
        }
        else
        {
            imageFrame = CGRectMake((height - width) / 2, 0, width, height);
        }
    }
    else if (mode == DWContentModeScaleAspectFill)//填充模式
    {
        CGFloat newHeight;
        CGFloat newWidth;
        if (originScale > 1) {
            newHeight = width;
            newWidth = newHeight * originScale;
            imageFrame = CGRectMake( -(newWidth - newHeight) / 2, 0, newWidth, newHeight);
        }
        else
        {
            newWidth = height;
            newHeight = newWidth / originScale;
            imageFrame = CGRectMake(0, - (newHeight - newWidth) / 2, newWidth, newHeight);
        }
    }
    else//拉伸模式
    {
        imageFrame = CGRectMake(0, 0, maxV, maxV);
    }
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(maxV, maxV), NO, scale);//以最大长度开启图片上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, maxV, maxV) cornerRadius:radius] addClip];//绘制一个圆形的贝塞尔曲线,并做遮罩
    [self drawInRect:imageFrame];//在指定的frame中绘制图片
    CGContextRotateCTM(context, M_PI_2);
    image = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获取图片
    UIGraphicsEndImageContext();//关闭上下文
    return image;
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值