首页 文章

UINavigationBar带有iOS5的图像和默认渐变背景

提问于
浏览
3

我正在尝试使用iOS5中的新 [UINavigationBar appearance] 功能将徽标图像添加到我的应用程序中的UINavigationBars . 首先,我想保留默认渐变,但在导航栏中居中一个透明的png . 徽标图像大约120像素宽(240像素@ 2x) .

我首先通过设置背景图像来尝试这个 . setBackgroundImage:forBarMetrics: 的默认行为似乎是平铺图像,所有透明部分显示默认的导航栏背景颜色,黑色 . 我也可以通过外观修改器设置背景颜色,并获得平坦的颜色背景,但我真的想获得原始的渐变行为而不为它维护单独的图像资源 . 它还可以更容易地调整代码,因为我可以在那里调整色调,而不是在我决定更改它时重新生成新图像 .

我正在尝试使用的内容:

UIImage *logoImage = [UIImage imageNamed:@"logoImage"];
[[UINavigationBar appearance] setBackgroundImage:logoImage forBarMetrics:UIBarMetricsDefault];

1 回答

  • 0

    你可以用两种方法做到这一点 . 如果要始终在导航栏中显示图像,请创建图像视图并将其设置为导航栏的子视图:

    [self setLogoImageView:[[UIImageView alloc] init]];
    [logoImageView setImage:[UIImage imageNamed:@"logo.png"]];
    [logoImageView setContentMode:UIViewContentModeScaleAspectFit];
    
    CGRect navFrame = [[navController navigationBar] frame];
    
    float imageViewHeight = navFrame.size.height - 9;
    
    float x_pos = navFrame.origin.x + navFrame.size.width/2 - 111/2;
    
    float y_pos = navFrame.size.height/2 - imageViewHeight/2.0;
    
    CGRect logoFrame = CGRectMake(x_pos, y_pos, 111, imageViewHeight);
    
    [logoImageView setFrame:logoFrame];
    [[[self navigationController] navigationBar] addSubview:logoImageView];
    

    如果您只想在特定视图中显示徽标,请设置视图的导航项:

    [logoImageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    [[self navigationItem] setTitleView:logoImageView];
    

相关问题