2014-03-03 26 views
0

繪製簡單的形狀時,我有,通過座標的字符串循環,並繪製使用UIBezierPath的形狀的應用程序。當我運行的應用程序,我得到以下錯誤:錯誤在Objective-C

<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0. 

下面是一個切下來的我一直用來測試的代碼版本,並嘗試和解決此錯誤:

UIBezierPath *testPath = [UIBezierPath bezierPath]; 

[[UIColor blackColor] setStroke]; 
[[UIColor redColor] setFill]; 

CGContextRef testPathRef = UIGraphicsGetCurrentContext(); 

[testPath moveToPoint:CGPointMake(100, 100)]; 
[testPath addLineToPoint:CGPointMake(200, 100)]; 
[testPath addLineToPoint:CGPointMake(100, 200)]; 
[testPath fill]; 
[testPath stroke]; 
[testPath setLineWidth:5]; 
[testPath closePath]; 

蘋果自己的文檔似乎表明,以上是我需要繪製一個簡單的形狀,並着色它,它輕描淡寫地提到一個「背景」,但它是可選的。我已經看過涉及這種錯誤的其他問題,有些人似乎建議一個對象爲空(0x0),但我無法弄清楚發生了什麼問題。

編輯:我創建了一個新的歸類稱爲CreateButtons這是一個子類的UIView,並呼籲,但drawRect方法似乎永遠不會被解僱。

-(void)drawShape:(NSString*)locationString buttonTagged:(NSInteger)buttonTag{ 

    CreateButtons *createButtonsInstance = [[CreateButtons alloc] init]; 

} 

CreateButtons實現:

#import "CreateButtons.h" 

@implementation CreateButtons 

-(id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame]; 

    if (self) { 
     NSLog(@"initWithFrame fired"); 

    } 
    return self; 
} 

-(void)drawRect:(CGRect) rect { 
    NSLog(@"Draw rect fired"); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 

    CGContextMoveToPoint(context, 100, 100); 
    CGContextAddLineToPoint(context, 150, 150); 
    CGContextAddLineToPoint(context, 100, 200); 
    CGContextAddLineToPoint(context, 50, 150); 
    CGContextAddLineToPoint(context, 100, 100); 

    CGContextStrokePath(context); 
} 

回答

0

只要確保你調用此代碼時的上下文是有效的。這是隻有在UIView子類的內部drawRect:方法。你可能需要修改你的代碼以這種方式工作,因爲這是一個基本的iOS實踐。在這種情況下,操作系統爲您設置正確的CGContext

否則,你可能需要創建自己的CGContext

+0

好了,所以我需要我的代碼進入 - (空)的drawRect(的CGRect)RECT,但是當我把它,有什麼事我需要通過呢?我繪製的形狀與許多側面/角落組合都不同。 – Ryan

+0

你永遠不應該自己調用drawRect - 再次因爲上下文。你的iOS應用程序由許多視圖組成。您應該創建儘可能多的視圖,並且每個視圖都可以呈現您喜歡的形狀。或者你可以有一個單一的視圖做所有的繪圖。 – Legoless

+0

我用新的代碼編輯了我的問題。我曾嘗試添加一個類,當負載應繪製形狀? – Ryan