2012-10-24 54 views
0

我正在使用Iphone應用程序。我想有一個小的隱形廣場網格。以網格編程的顏色單元

我希望能夠從代碼中更改這些方塊的顏色。

我該怎麼做?

其他信息:

網格是靜態的(某種一個棋格的),我需要能夠改變一個給定的正方形的顏色在裏面。例如將方塊C3的顏色更改爲紅色,將E7更改爲綠色。

我不想把任何內容放在方格以外的顏色上。

回答

1

你也可以繼承的UIView,添加一些數據結構來保存細胞的信息,並覆蓋drawRect:方法。

事情是這樣的:

// in view 

-(void)drawCellAtRow:(int)row column:(int)column 
{ 
    // draw a cell   
} 

-(void)drawRect:(CGRect)rect 
{ 
    // determine which cells have to be drawn for this rect 
    // and draw them 
} 
-(void)changeCellAtRow:(int)row column:(int)column 
{ 
    // change cell info 
    // calculate rect to update 
    [self setNeedsDisplayInRect:dirtyRect]; 
} 

// in view controller 
-(void)eventHandler 
{ 
    [cellView changeCellAtRow:row column:column]; 
} 

Drawing guide for iOS

0

theView.backgroundColor = color;

+0

謝謝,但我需要至少100X100的小方塊,所以我不確定擁有10000視圖是個好主意。 – Youssef

0

當我想創建一個視圖,42子視圖(電網) - 我只是用的drawRect和drawed在合適的崗位必需的色彩漸變和在他們身上 - 繪製了必要的文字。 (我也需要不同的方塊在不同的漸變色,如果你需要還 - 我相信你可以調整這個代碼進一步:))

- (void)drawRect 
{ 
    int mWidth = 99; 

    int mHeight = 99; 

    //--- now we draw all gradients (will have 1 pix wide space between each) 
    for(int i = 0; i < 100; i++) 
    { 
     for(int j = 0; j < 100; j++) 
     { 

      //--- gradient color 
      CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); 

      CGFloat colors [] = { //these values are for a white square block. 
        255/255.0, 255/255.0, 255/255.0, 1.0, 
        255/255.0, 255/255.0, 255/255.0, 1.0 
       }; 

      CGGradient gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2); 

      CGColorSpaceRelease(baseSpace), baseSpace = NULL; 


      CGContextSaveGState(context); 

      CGContextAddRect(context, rect); 

      CGContextClip(context); 

      CGContextAddRect(context, CGRectMake(1+j*(mWidth+1),0+i*(mHeight+1),mWidth,mHeight+i*mHeight+i*1)); 

      CGContextClip(context); 


      //+ 1 values to make sure we have one pix wide space between any two squares 
      CGContextDrawLinearGradient (context, gradient, CGPointMake(1+j*(mWidth+1), 0+i*(mHeight+1)), CGPointMake(1+j*(mWidth+1),0+mHeight+i*mHeight+i*1), 0); 

      CGGradientRelease(gradient), gradient = NULL; 

      CGContextRestoreGState(context); 
      //=== 

      //Here We can draw any string labels we need. 
     } 
    } 

祝你好運!