Reputation: 56
I have a scene of storyboard with a UIVIewcontroller. Inside this scene i have a UIImageview that contains the background image, an UIButton, and an UIView.
This UIView have a overrided drawRect method with:
- (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);
}
My question Is: How can i set an image as background of this my custom UIView and drawing rectangles over it?
Regards
Upvotes: 1
Views: 2756
Reputation: 5831
Let's say you named your UIView subclass MyCustomView. When adding an UIView from interface-builder (xib or storyboard), you MUST explicitly set the custom class of the UIView from interface builder to be MyCustomView (like in this answer).
Another problem that might occur is the order of the views. Which one is on top?
Adding the custom view from code is another way to do it.
Your drawing code seems ok. Here is my code from drawRect
that draws an image in the background (I tweaked it a little bit):
- (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++;
}
}
Upvotes: 5
Reputation: 16276
This is to set a background image for your custom UIView
(put inside drawRect:
method):
self.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"someimage.png"]];
If you want to add subviews to the custom UIView
, either you do that directly on storyboard or by using addSubview
method programmatically:
UIView *v = [[UIView alloc]initWithFrame:CGRectMake(x,y,w,h)];//change x,y,w,h to meet yours
[self.myCustomView addSubview:v];
Of course, addSubview
will handle all UIView
subclasses, so you can add UIImageView
, UIScrollView
, etc.
Upvotes: 0