【问题标题】:Can I apply a texture to UIToolbar?我可以将纹理应用到 UIToolbar 吗?
【发布时间】:2010-03-26 01:28:34
【问题描述】:

我试过这样做:

[toolbar setTint:[UIColor colorWithPatternImage:[UIImage imageNamed:@"thingFromMyBundle.png"]]];

但它只是以黑色结束。起初我以为你不允许用纹理“着色”,但我最近看到了可以做到这一点的应用程序。我错过了什么吗?

谢谢。

【问题讨论】:

    标签: iphone colors textures uitoolbar


    【解决方案1】:

    将 2 个文件添加到您的项目中,例如将它们命名为 UINavigationBar-CustomTexture.hUINavigationBar-CustomTexture.m,在这些文件中输入:

    .h 文件:

    #import <UIKit/UIKit.h>
    @interface UINavigationBar (CustomTexture)
    @end
    

    .m 文件:

    #import "UINavigationBar-CustomTexture.h"
    
    @interface UIView (CustomTexture)
    - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;
    @end
    
    @implementation UINavigationBar (CustomTexture)
    - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
        if ([self isMemberOfClass:[UINavigationBar class]]){
            UIImage *image = [UIImage imageNamed:@"myImage.png"];
            CGContextScaleCTM(ctx, 1.0f, -1.0f);
            CGContextDrawImage(ctx, CGRectMake(0, -image.size.height, self.frame.size.width, self.frame.size.height), image.CGImage);
        }else{
            [super drawLayer:layer inContext:ctx];
        }
    }
    @end
    

    包括您在其中实例化导航控制器的 .h 文件。 将您的 png 文件设置为 320x44。根据您的纹理,将导航栏的色调更改为类似这样(以使导航栏上的按钮看起来更好):

    [self.navigationController.navigationBar setTintColor:[UIColor colorWithHue:0 saturation:0 brightness:0.5f alpha:0.1f]];
    

    【讨论】:

    • 它对我有用,但我得到一个“:doClip:空路径。”。如果我删除 CGContextClip(ctx);他们警告消失了(一切仍然有效)。
    • 一般来说,类别确实不是处理自定义绘图的好方法。您正在覆盖 UINavigationBar 的标准实现(如果有的话)并且从不调用该实现。子类化是处理它的正确方法,但它需要更多的工作来设置 xib 文件中导航栏的类,但更适合未来。
    【解决方案2】:

    这是我解决这个问题的方法:

    _titleToolbar= [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth, 34.0f)];
    [_titleToolbar setTranslucent:YES];
    [_titleToolbar setBackgroundColor:[UIColor clearColor]];
    
    CALayer* backgroundLayer = [CALayer layer];
    [backgroundLayer setFrame:CGRectMake(0, 0, kDeviceWidth, _titleToolbar.frame.size.height)];
    
    UIImage* patternImage = [UIImage deviceImageNamed:@"topToolbarBackground"];
    [backgroundLayer setBackgroundColor:[UIColor colorWithPatternImage:patternImage].CGColor];
    [[_titleToolbar layer] insertSublayer:backgroundLayer atIndex:0];
    

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多