2013-12-08 47 views
0

我創建了一個cust UIView類,以便我可以顯示Map對象的內容。經過大量的研究,我仍然無法確定爲什麼下面的方法不畫任何東西:UIImage drawinrect方法不繪製圖像

- (void)drawRect:(CGRect)rect 
{ 
    if(_map!=nil){ 
     UIGraphicsBeginImageContext(rect.size); 
     UIImage *img = [UIImage imageNamed:@"grass"]; 
     float w = rect.size.width/_map.width; 
     float h = rect.size.height/_map.height; 
     for(int x=0; x<_map.width; x++){ 
      for(int y=0; y<_map.height; y++){ 
       Tile *tile = [_map getTileAtX:x Y:y]; 
       UIImage *img = [UIImage imageNamed:NSStringFromTileType(tile.type)]; 
       [img drawInRect:CGRectMake(x*w, y*h, w, h)]; 
      } 
     } 
     UIGraphicsEndImageContext(); 
    } 
} 

我打電話[mapView setNeedsDisplay]刷新UIView的。

任何幫助將不勝感激。謝謝!

+1

如果您在該「」UIGraphicsBeginImageContext「」行上設置斷點,Xcode是否會停在那裏? –

回答

3

在您的代碼UIGraphicsBeginImageContext(...)推動視圖上下文的新的圖像上下文和drawInRect:繪製圖像到這個新的上下文。 UIGraphicsEndImageContext()彈出圖像上下文丟棄它的內容。推送圖像上下文通常用於當你想創建 UIImage,而不是當你需要繪製其內容到上下文中。

如果你想看到圖像 - 刪除UIGraphicsBeginImageContextUIGraphicsEndImageContext調用。

+0

太棒了!它節省了我的時間!在經過大量搜索之後,我找到了這個答案,在此之前,我認爲我可能無法在當前視圖中的某處繪製圖像!謝謝親愛的 –