1

UIVIewcontroller を使用したスト​​ーリーボードのシーンがあります。このシーン内には、背景画像、UIButton、および UIView を含む UIImageview があります。

この UIView には、次のようにオーバーライドされた drawRect メソッドがあります。

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


    CGFloat height = self.bounds.size.height;
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextClearRect(context, rect);
    CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
    CGFloat barWidth = 30;
    int count = 0;
    NSArray *values = [NSArray arrayWithObjects:@1, @0.5, nil];
    for (NSNumber *num in values) {
        CGFloat x = count * (barWidth + 10);
        CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);
        CGContextAddRect(context, barRect);
        count++;
    }
    CGContextFillPath(context);

}

私の質問は次のとおりです:このカスタムUIViewの背景として画像を設定し、その上に長方形を描画するにはどうすればよいですか?

よろしく

4

2 に答える 2

5

UIView サブクラスに MyCustomView という名前を付けたとします。インターフェイス ビルダー (xib またはストーリーボード) から UIView を追加するときは、インターフェイス ビルダーから UIView のカスタム クラスを MyCustomView に明示的に設定する必要があります (この回答のように)。

発生する可能性のある別の問題は、ビューの順序です。どっちが上?

コードからカスタム ビューを追加することも、別の方法です。

あなたの描画コードは問題ないようです。バックグラウンドで画像を描画するコードはdrawRect次のとおりです(少し調整しました):

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);

    // here I draw an image BEFORE drawing the rectangles
    UIImage* img = [UIImage imageNamed:@"img.jpg"];
    [img drawInRect:rect];

    CGFloat height = self.bounds.size.height;
    CGFloat barWidth = 30;

    CGContextSetFillColorWithColor(context, [[UIColor grayColor] CGColor]);

    int count = 0;
    NSArray *values = [NSArray arrayWithObjects:@1, @0.5, nil];
    for (NSNumber *num in values) {
        CGFloat x = count * (barWidth + 10);
        CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);

        // drawing rectangles OVER the image
        CGContextFillRect(context, barRect);
        count++;
    }
}
于 2013-08-11T12:27:25.600 に答える
0

これは、カスタムの背景画像を設定することですUIViewdrawRect:メソッド内に配置):

 self.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"someimage.png"]];

サブビューを custom に追加する場合UIViewは、ストーリーボードで直接行うか、addSubviewプログラムでメソッドを使用して行います。

UIView *v = [[UIView alloc]initWithFrame:CGRectMake(x,y,w,h)];//change x,y,w,h to meet yours
[self.myCustomView addSubview:v];

もちろん、addSubviewはすべてのサブクラスを処理するので、、 などUIViewを追加できます。UIImageViewUIScrollView

于 2013-08-10T14:21:42.607 に答える