2011-08-26 105 views
1

我沿着動畫在iPhone上的路徑的對象。代碼使用CAKeyframeAnimation很有效。爲了調試目的,我想在屏幕上畫線。我似乎無法使用當前的CGContextRef。無論我看到它說你需要繼承UIView,然後重寫drawRect方法在屏幕上繪製。有沒有辦法解決?如果不是,我如何將數據傳遞給drawRect方法,以便知道繪製的內容?繪製路徑 - iPhone

編輯: 確定。我結束了UIView子類並在drawRect方法中實現了繪圖。我可以得到它通過創建子類的視圖(稱爲drawPath)另一種方法來繪製到屏幕上,設置一個實例變量,然後調用setNeedsDisplay。這又會觸發使用實例變量繪製到屏幕上的drawRect方法。這是最佳做法嗎?如果我想繪製20多條路徑會發生什麼。我不應該爲所有這些創建屬性。

回答

6

在的UIView你的drawRect方法把這樣

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetRGBStrokeColor(context, 1.0, 0,0 , 0.0); 
CGContextSetLineWidth(context, 3.f); 

CGContextBeginPath(context); 
CGContextMoveToPoint(context,x1,y1); 

CGContextAddLineToPoint(context, x2 , y2); 
CGContextStrokePath(context); 
0

如果你想使用核心圖形繪製使用CALayer。如果您不想將其繼承,請將繪圖委託給視圖。

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     CALayer* myLayer = [CALayer new]; 
     myLayer.delegate = self; 
     self.layer = myLayer; 
    } 
} 

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{ 
    // draw your path here 
} 

當你需要重畫它時,別忘了打電話給[self.layer setNeedsDisplay];

+0

一些代碼,我可以使用視圖控制器內的代碼? – user472292

+0

您可以在viewDidLoad方法實現它。將圖層設置爲視圖,委託給視圖控制器。 – Davyd