mis*_*tic 1 uiviewcontroller uiview drawrect ios
我有一个带有UIVIewcontroller的故事板场景.在这个场景中,我有一个包含背景图像的UIImageview,一个UIButton和一个UIView.
这个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);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我怎样才能将图像设置为我的自定义UIView的背景并在其上绘制矩形?
问候
假设您将UIView子类命名为MyCustomView.从interface-builder(xib或storyboard)添加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++;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2728 次 |
| 最近记录: |