How to put an image in the center of navigationBar of a UIViewController?

后端 未结 7 2266
耶瑟儿~
耶瑟儿~ 2021-02-01 05:31

I have this snippet of code used in viewDidLoad of a UIViewController. I\'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.



        
7条回答
  •  爱一瞬间的悲伤
    2021-02-01 05:58

    Perhaps not what you meant, but I ran into this page looking for a way to provide a centered background image for the navigation bar, so in case you're here for that... here's one way.

    Stealing a little bit from another answer, you can break your image into foreground and background, then build a new image that stretches the background and centers the foreground, and then set that as your nav bar's background image. Building the image works like so:

    // build an image by stretching the bg, then merging it with the fg
    CGSize barSize = self.navController.navigationBar.frame.size;
    UIImage *fg = [UIImage imageNamed:@"some_fg"];
    UIImage *bg = [[UIImage imageNamed:@"some_bg"]
                   resizableImageWithCapInsets:UIEdgeInsetsMake(0.f,1.f,0.f,1.f)];
    UIGraphicsBeginImageContextWithOptions(barSize, NO, 0.0);
    [bg drawInRect:CGRectMake(0, 0, barSize.width, barSize.height)];
    [fg drawInRect:CGRectMake((barSize.width-fg.size.width)/2.f,
                              0,
                              fg.size.width,
                              fg.size.height)];
    // grab the merged images
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

提交回复
热议问题