如何以编程方式渲染平面背景 UIColor 作为 UIToolbar 的背景?
因此,我遵循了一个教程,该教程允许我对 UIToolbar 进行子类化并绘制图像作为 UIToolbar 的自定义背景。
代码是这样的:
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
UIImage *backgroundImage = [UIImage imageNamed:@"toolbar_background.png"];
[backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
这可以完美地工作。考虑到我只希望我的工具栏背景是纯色。基本上像[UIColor blackColor],有没有更简单的方法在drawRect方法中做到这一点?
当 [UIColor blackColor] 可用时,必须制作 320 x 44 px 高度的纯黑色背景图像并将其与上述代码一起使用似乎是极大的开销?我只是不确定如何在这里实现它。
我想过做这样的事情:
- (void)drawRect:(CGRect)rect
{
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];
test.backgroundColor = [UIColor blackColor];
[self addSubview:test];
}
但这不起作用,因为 UIView COVERS 我稍后添加的所有 UIToolbar 项目,即工具栏是黑色的,是的,但黑色覆盖了所有工具栏项目,使它们不可见。
有解决方法吗?
谢谢。
So I followed a tutorial which allows me to subclass UIToolbar and draw an image as a custom background for the UIToolbar.
Code was something like this:
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
UIImage *backgroundImage = [UIImage imageNamed:@"toolbar_background.png"];
[backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
This works flawlessly. Considering though that I just want my toolbar background to be a flat color. Basically something like [UIColor blackColor], is there an easier way to do this in the drawRect method?
Having to make a 320 x 44 px height flat black background image and use that with the above code seems like extreme overhead when [UIColor blackColor] is available? I'm just not sure how to implement it here.
I thought about doing something like this instead:
- (void)drawRect:(CGRect)rect
{
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];
test.backgroundColor = [UIColor blackColor];
[self addSubview:test];
}
But this doesn't work because then the UIView COVERS all the UIToolbar items that I add later i.e the Toolbar is black yes, but the black is overtop all the toolbar items so they are not visible.
Is there a workaround?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如第一个示例所示,重写
-drawRect:
方法,但不绘制图像,而是使用UIRectFill
方法,如下所示:Override the
-drawRect:
method as in your first example, but instead of drawing an image, use theUIRectFill
method, like this:您可以创建一个平面 UIToolbar,而无需创建子类。只需设置BackgroundColor、BackgroundImage 和ShadowImage。
You can create a flat UIToolbar without the need to create a subclass. Simply set BackgroundColor, BackgroundImage and ShadowImage.