简体   繁体   中英

Scale Image in NavigationItem.TitleView to fit inside of the UINavigationBar

I am new to iOS development but not so new to C#. I chose to do the tutorial provided by Xamarin/Microsoft and then to try and expand on that. I was looking for a way to set an image in the center of the UINavigationBar, and I found that the proper way to do so was to use NavigationItem.TitleView = myImageView;

This works great! However, there is one issue: the image I used is simply bigger than the NavigationBar. I want to scale (and keep the aspect ratio) the image to fit inside of the NavigationBar while also looking nice. Here is what I've done up to this point to get the image:

var logo = UIImage.FromFile("PolarisLogoBlank.png");
var iView = new UIImageView(logo);

NavigationItem.TitleView = iView;

And here is a picture of what I'm getting:

在此处输入图片说明

Any help is much appreciated; thanks SO!

You have to set both the height of the imageView and the contentMode of the imageView so that the image is not stretched. This is what you are looking for:

iView.contentMode = .scaleAspectFit
if let navigationController = navigationController  {
    iView.frame.size.height = navigationController.navigationBar.frame.size.height
}

or with force unwrapping

iView.contentMode = .scaleAspectFit
iView.frame.size.height = navigationController!.navigationBar.frame.size.height

You can set the size of the imageView :

iView.frame.size.height = self.navigationController.navigationBar.frame.size.height;

I'm not sure what exactly that looks like in C#, but that's how you'd do it in Objective-C.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM