调用UIGraphicsBeginImageContextWithOptions invalid context 0x0.

问题出现场景:使用SDWebImage下载网络图片,下载完后然后处理圆角,有时会返回 CGContextSaveGState: invalid context 0x0. 

-(UIImage *)circleImageWithSize:(CGSize)size image:(UIImage *)image
{   
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
    [path addClip];
    [image drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

问题出现原因:传入的CGSize为0,导致生成的CGContextRef为空。

解决办法:处理图片之前判断下CGSize;

-(UIImage *)circleImageWithSize:(CGSize)size image:(UIImage *)image
{
    //处理 CGContextAddPath: invalid context 0x0 的问题
    if(size.height <= 0 || size.width <= 0){
        return nil;
    }
    
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
    [path addClip];
    [image drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

参考:

http://cache.baiducontent.com/c?m=9d78d513d9841afa18bed624564796364e01db3f678883402885ce14d5331107506793fe7c644a13d2b5212547f41400abe736036c5f64e4c593de5dddcac37573ce707e360b863010990eaebb4432c050875a9ebb5ea7e4ff68d5e89092c85520d74e443cd3a1d20744438a3bae4974f4a6ee1948000df9aa6724b9022a75de3e40b04dfce4326c07&p=8b2a970280985bb342bd9b7c61&newp=c07bd515d9c157b70be296625c53d8304a02c70e3ac3864e1290c408d23f061d4862e5b125251003d3c6776705a44a56e9f6307123454df6cc8a871d81ed8430&user=baidu&fm=sc&query=UIGraphicsBeginImageContextWithOptions+++invalid+context+0x0%2E&qid=ea59f7d000015e25&p1=1

转载于:https://my.oschina.net/mexiaobai1315/blog/1586495

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值