2013-04-22 157 views
0

我們如何以編程方式繪製背景圖案(設置爲UIImageView),如下所示?使用交替顏色繪製圖像

enter image description here

它具有交替的顏色的方塊像20×20像素。我可以用REAL Stupid和MS Visual Basic來完成。我從來沒有用iOS做過。如果我運行搜索,我得到的一條線索是colorWithPatternImage。幾年前,我使用了以下真正愚蠢的代碼。它可以工作,不管畫布的尺寸如何(相當於UIImageView)。

Dim i,j As Integer 
For j=0 To Ceil(CanvasX.Height/20) 
For i=0 To Ceil(CanvasX.Width/20) 
    If i Mod 2=0 And j Mod 2=0 Then 
    If CField1.text="1" Then 
     g.ForeColor=&cCC9900 
    Elseif CField1.text="2" Then 
     g.ForeColor=&c000000 
    Else 
     g.ForeColor=&cCCCCCC 
    End if 
    Elseif i Mod 2>0 And j Mod 2>0 Then 
    If CField1.text="1" Then 
     g.ForeColor=&cCC9900 
    Else 
     g.ForeColor=&cCCCCCC 
    End if 
    Else 
    If CField1.text="1" Then 
     g.ForeColor=&cE6E6E6 
    Else 
     g.ForeColor=&cFFFFFF 
    End if 
    End if 
    g.FillRect i*20,j*20,20,20 
Next i 
Next j 

謝謝你的幫忙。

回答

1

方法#1:利用這個圖像:

enter image description here

然後通過指定一個圖案圖像設置背景顏色:

UIImage *bgImage = [UIImage imageNamed:@"squares"]; 
UIColor *bgColor = [UIColor colorWithPatternImage:bgImage]; 
someView.backgroundColor = bgColor; 

方法2:使用石英。子類UIView,然後執行以下方法:

- (void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    NSLog(@"%@", ctx); 

    CGFloat ws = self.frame.size.width; 
    CGFloat hs = self.frame.size.height; 

    const int side = 10; 

    int nx = ws/side; 
    int ny = hs/side; 

    CGRect rects[nx/2]; 

    for (int i = 0; i < ny; i++) { 
     for (int j = 0; j < nx; j += 2) { 
      rects[j/2] = CGRectMake(j * side, i * side, side, side); 
     } 

     const static CGFloat w[4] = { 1.0, 1.0, 1.0, 1.0 }; 
     const static CGFloat g[4] = { .75, .75, .75, .75 }; 

     if (i % 2) { 
      CGContextSetFillColor(ctx, g); 
     } else { 
      CGContextSetFillColor(ctx, w); 
     } 
     CGContextFillRects(ctx, rects, nx/2); 

     for (int j = 1; j < nx; j += 2) { 
      rects[j/2] = CGRectMake(j * side, i * side, side, side); 
     } 


     if (i % 2) { 
      CGContextSetFillColor(ctx, w); 
     } else { 
      CGContextSetFillColor(ctx, g); 
     } 
     CGContextFillRects(ctx, rects, nx/2); 
    } 
} 
+0

非常感謝。方法#2是我正在尋找的。美好的一天... – 2013-04-22 17:35:13