ios - 这个错误是什么无效上下文0x0?

标签 ios cocoa-touch cgcontext quartz-2d

我在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];
  }

在控制台中我看到了

 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

最佳答案

您应该将该自定义绘图代码移出 viewDidLoad,并将其移至 drawRect。

如果您想实现自己的 drawRect 方法,您还需要将 View 子类化。

查看此示例:http://ykyuen.wordpress.com/2010/08/27/iphone-uiview-with-border/

关于ios - 这个错误是什么无效上下文0x0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6597982/

相关文章:

ios - Apple 的 web 服务操作不成功并且无法对包进行身份验证?

ios - 调整大小后使用自动布局以编程方式将 UIImageVIew 居中

ios - AsyncSocket 在 iPad 的 sleep 模式下崩溃

objective-c - 加快检查点像素颜色的速度

ios - 在 iOS 中绘图时计算控制点

ios - 对成员 '+' 的引用不明确 - 尝试在字符串扩展中递增整数变量

iphone - 没有输入 Switch 语句?

iphone - 当键盘滑入时如何禁用导航栏中的 'Done' 按钮?

objective-c - 在文本上绘制两个阴影(核心图形)

iOS ARC Fire and Forget 异步包装的最佳实践