What this error is invalid context 0x0?

怎甘沉沦 提交于 2019-12-12 08:55:04

问题


I wrote the following code in ViewDidLoad

// Implement viewDidLoad to do additional setup after loading the view, typically     from      a nib.
     -(void)viewDidLoad {
    [super viewDidLoad];

NSString *str = [NSString stringWithFormat:@"Veer"];

CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
CGFloat values[4] = {55.0, 0.0, 0.0, 1.0}; 
CGColorRef glowColor = CGColorCreate(rgbColorspace, values); 
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor( context, CGSizeMake( 5.0, 0.0 ), 20.0f, glowColor);   
[str drawAtPoint:CGPointMake(10.5f, 0.5f) withFont:[UIFont      fontWithName:@"Helvetica" size:100.0f]];    
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 200, 250, 100)];
[label setBackgroundColor:[UIColor clearColor]];
label.font=[UIFont fontWithName:@"DBLCDTempBlack" size:50.0];
label.textColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
[label setText:str];

[self.view addSubview:label];
  }

In Console I saw as

 Testing Clock[3286] <Error>: CGContextSetStyle: invalid context 0x0
 Testing Clock[3286] <Error>: CGContextSetFont: invalid context 0x0
 Testing Clock[3286] <Error>: CGContextSetTextMatrix: invalid context 0x0
 Testing Clock[3286] <Error>: CGContextSetFontSize: invalid context 0x0
 Testing Clock[3286] <Error>: CGContextSetTextPosition: invalid context 0x0
 Testing Clock[3286] <Error>: CGContextShowGlyphsWithAdvances: invalid context 0x0

回答1:


You should move that custom drawing code out of viewDidLoad and move it to drawRect.

You will also need to subclass the view if you want to implement your own drawRect method.

Checkout this example: http://ykyuen.wordpress.com/2010/08/27/iphone-uiview-with-border/




回答2:


You just have to check if context exist before drawing :

CGContextRef context = UIGraphicsGetCurrentContext();
if (context) {
    // Do your stuff
}


来源:https://stackoverflow.com/questions/6597982/what-this-error-is-invalid-context-0x0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!