代码之家  ›  专栏  ›  技术社区  ›  lostInTransit

在横向模式下为uinavigationbar自定义背景

  •  7
  • lostInTransit  · 技术社区  · 16 年前

    我正在为我的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];
    
    6 回复  |  直到 9 年前
        1
  •  3
  •   Ben Gottlieb    16 年前

    您可能需要设置背景图像视图的自动调整大小掩码;请尝试使用 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight

        2
  •  6
  •   Ivan Karpan    16 年前

    在两种屏幕方向模式中,最好使用

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

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

        3
  •  6
  •   ljonesATL    15 年前

    经过一番研究,追踪和错误,我找到了一个解决办法,当你进入电影播放模式时,它不会取代导航栏。希望这不会对应用程序的批准造成问题,但基于本文,我认为这应该是好的:

    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
    
        4
  •  1
  •   lostInTransit    16 年前

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

        5
  •  1
  •   Ahmet Ardal    14 年前

    通过检查导航栏实例的帧大小,可以为不同的方向提供不同的图像,从而更改纵向和横向方向的图像:

    - (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);
    }
    

    this complete demo Xcode project 自定义uinavigationbar的外观可能会有所帮助。它还包括@2X版本的背景图像,以支持iPhone4设备上的视网膜显示。

        6
  •  0
  •   Nuthatch    15 年前

    尝试更简单的方法 [UIImage imageNamed:@"navbar_landscape.png"] 因为ui元素正是 想象中的: 正如Ljonesatl所显示的那样,是为。