无法在自定义UIView中的图像上绘制矩形

时间:2013-08-10 14:06:54

标签: ios uiview uiviewcontroller drawrect

我有一个带有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的背景并在其上绘制矩形?

此致

2 个答案:

答案 0 :(得分:5)

假设您将UIView子类命名为MyCustomView。从interface-builder(xib或storyboard)添加UIView时,必须将UIView的自定义类从接口构建器显式设置为MyCustomView(如此answer中所示)。

可能出现的另一个问题是视图的顺序。哪一个在顶部?

从代码中添加自定义视图是另一种方法。

您的绘图代码似乎没问题。以下是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++;
    }
}

答案 1 :(得分:0)

这是为自定义UIView设置背景图片(放在drawRect:方法内):

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

如果您要将子视图添加到自定义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等。

相关问题