一、問題描述
下載圖片,然后用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的值。