一、问题描述
下载图片,然后用Quartz2D绘制缩放的图片,运行无法显示图片并且编译器警告:
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextSetBlendMode: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextSetAlpha: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextTranslateCTM: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextScaleCTM: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Aug 18 21:41:50 02_计算UITableViewCell的行高[16777] <Error>: CGContextRestoreGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
二、问题分析
有人说因为设置app的状态栏样式的使用了旧的方式,一般式iOS6的时候使用这种方式,iOS7、8也兼容,但是到了iOS9就报了警告。在info.plist里面设置了View controller-based status bar appearance为NO,要设置为YES。
但View controller-based status bar appearance设置YES后,问题还是没解决。
后来发现只要执行以下代码都会警告:
1 - (void)setImageView
2 {
3 NSString *url = @"http://ww3.sinaimg.cn/large/005P1ePojw1f6xzt7o6saj30go4w8wna.jpg";
4 // 设置图片
5 __weak typeof(self) weakSelf = self;
6 [self.imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
7 // 开启图形上下文
8 UIGraphicsBeginImageContextWithOptions(weakSelf.size, YES, 0.0);
9 // 将下载完的image对象绘制到图形上下文
10 CGFloat width = weakSelf.size.width;
11 CGFloat height = width * 520 / 300;
12 [image drawInRect:CGRectMake(0, 0, width, height)];
13 // 获得图片
14 weakSelf.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
15 // 结束图形上下文
16 UIGraphicsEndImageContext();
17 }];
18 }
后来发现问题出现在这处: UIGraphicsBeginImageContextWithOptions(weakSelf.size, YES, 0.0);
因为weakSelf.size的值CGSizeMake(0, 0),导致错误。
三、问题解决
重新设置self.size的值。