0

次のように、プログラムで背景パターン ( UIImageViewに設定する) をどのように描画できますか?

ここに画像の説明を入力

20 x 20 ピクセルのような色の正方形が交互に並んでいます。REAL Stupid と MS Visual Basic でできます。私はiOSでそれをやったことがありません。検索を実行すると、colorWithPatternImageが手がかりの 1 つになります。私は数年前に次の REAL Stupid コードを使用しました。キャンバスのサイズに関係なく機能します (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

ご協力ありがとうございました。

4

1 に答える 1

1

アプローチ#1:この画像を撮ります:

ここに画像の説明を入力

次に、パターン イメージを指定して背景色を設定します。

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

アプローチ #2: Quartz を使用します。をサブクラス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);
    }
}
于 2013-04-22T16:45:21.880 に答える