7

我正在为我的 UINavigationBar 添加自定义背景。只要手机处于纵向模式,它就可以正常工作。一旦我切换到横向模式,一半的栏显示为蓝色(默认导航栏颜色),一半有我的图像

如何在横向模式下拉伸图像并在纵向模式下再次变小?

谢谢

解决方案
万一有人在寻找如何将图像添加到导航栏的答案 - 这里有

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 480.0, 44.0)];
[imgView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"navbar_landscape" ofType:@"png"]]];
[navigationController.navigationBar addSubview:imgView];
[imgView release];
4

6 回答 6

6

在两种屏幕方向模式下,使用起来要好得多

[navigationController.navigationBar insertSubview:imgView atIndex:0];

这会将图像视图置于所有其他视图之下,并且所有默认导航栏元素(标题、标准按钮)都可以正常工作。

于 2009-04-28T05:52:35.627 回答
6

经过一番研究和反复试验,我找到了一种解决方法,当您进入电影播放模式时,它不会取代导航栏。希望这不会导致应用程序批准出现问题,但根据这篇文章,我认为应该没问题:

http://developer.apple.com/iphone/library/qa/qa2009/qa1637.html

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    if([self isMemberOfClass: [UINavigationBar class]]){
        UIImage *image = [UIImage imageNamed:@"navBarBackground.png"];
        CGContextClip(ctx);
        CGContextTranslateCTM(ctx, 0, image.size.height);
        CGContextScaleCTM(ctx, 1.0, -1.0);
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
    }else{
        [super drawLayer:layer inContext:ctx];
    }
}

@end
于 2010-01-10T21:54:33.443 回答
3

您可能需要设置背景图像视图的 autoresizingMask;尝试使用UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight

于 2008-12-19T14:15:42.683 回答
1

Ben给出的解决方案确实解决了这个问题,但它在横向模式下拉伸了图像。我最终创建了两张图像 - 一张用于横向模式,另一张用于纵向模式。然后我在 shouldAutoRotate 中添加了代码以根据方向更改导航栏图像

于 2008-12-24T14:34:16.823 回答
1

您可以通过检查 UINavigation 栏实例的帧大小为不同的方向提供不同的图像来更改纵向和横向的图像:

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    if ([self isMemberOfClass:[UINavigationBar class]] == NO) {
        return;
    }

    UIImage *image = (self.frame.size.width > 320) ?
                        [UINavigationBar bgImageLandscape] : [UINavigationBar bgImagePortrait];
    CGContextClip(context);
    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
}

这个关于自定义UINavigationBar外观的完整演示 Xcode 项目可能会有所帮助。它还包括@2x 版本的背景图像,以支持 iPhone 4 设备上的视网膜显示。

于 2011-02-13T10:04:57.487 回答
0

尝试更简单的方法,[UIImage imageNamed:@"navbar_landscape.png"]因为 UI 元素正是imageNamed:的用途,如 ljonesATL 所示。

于 2010-01-20T16:31:42.860 回答