2011-11-02 103 views
3

我試圖在iOS5中使用新的[UINavigationBar appearance]功能將徽標圖像添加到我的應用程序中的UINavigationBars。首先,我想保留默認漸變,但在NavBar中居中放置一個透明png。徽標圖像寬度約爲120像素(240像素@ 2x)。UINavigationBar與圖像和默認漸變背景與iOS5

我第一次嘗試通過設置背景圖像。 setBackgroundImage:forBarMetrics:的默認行爲似乎是平鋪圖像,並且所有透明部分都顯示默認導航欄背景顏色黑色。我也可以通過外觀修改器設置背景顏色,並獲得平坦的顏色背景,但我真的很想獲得原始的漸變行爲,而無需爲其保留單獨的圖像資源。它還使代碼更容易調整,因爲我可以在那裏調整色調,而不是在我決定更改它時重新生成新圖像。

我試圖使用方法:

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

回答

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]; 
+0

硬編碼的數值過多... – JOM