如何在Xamarin表头上有动态图像?

时间:2017-03-04 23:17:50

标签: xamarin xamarin.forms openweathermap

我正在制作Xamarin表单,其标题标题右侧有天气温度和天气图标。

例如

纽约60'F SunnyIcon

我正在使用openweather api来获取数据。

问题是,我无法在Xamarin表头上创建动态图像持有者。

如何在Xamarin表头上创建动态图像?

附件是一个示例应用程序,我正在根据源代码工作,我从github下载...

enter image description here

2 个答案:

答案 0 :(得分:0)

我不确定“标题”是什么意思,但是如果你想在Navigation Bar添加一个图标,你可以通过在你的构造函数中调用ToolbarItems.add()来做到这一点。像这样的页面:

    public myPage()
    {
        InitializeComponent();
        ToolbarItems.Add(new ToolbarItem("Weather", "WeatherIcon.png", async () =>
        {
            //Code to Execute when Icon is tapped
        }));
    }

添加ToolbarItem时,第一个参数是项目的名称,第二个参数是将在导航栏末尾显示的图像的名称,最后一个是可选的,它会创建点击图标时执行的方法。

如果您需要根据当前天气不同的图标,您可以这样做:

    public myPage()
    {
        InitializeComponent();

        string weatherIconString = "";
        if(weather.isSunny) // Edit contition however you need
            weatherIconString = "SunnyIcon.png";
        else
            weatherIconString = "CloudyIcon.png";

        ToolbarItems.Add(new ToolbarItem("Weather", weatherIconString));
    }

答案 1 :(得分:0)

你必须像这样写一个自定义渲染器:结果: enter image description here

 public class CustomNavigationPageRenderer : NavigationRenderer
{

    public override void ViewDidLoad()
    {
        //I'm getting width and height so i can rescale the image
        nfloat navigationBarWidth = NavigationBar.Frame.Width;
        nfloat navigationBarHeight = NavigationBar.Frame.Height;

        //you can load image from your bundle,so you can add your weather icons on bundle -> under Resources folder
        var img = UIImage.FromBundle("navigationbarbackground.jpg");
        //create image context to draw image
        UIGraphics.BeginImageContextWithOptions(new CGSize(navigationBarWidth, navigationBarHeight), true, 0);
        //I'm filling the background with a color so it is the same as with my background image color    
        UIColor.FromRGB(54, 60, 65).SetFill();
        UIGraphics.RectFill(new CGRect(0, 0, navigationBarWidth, navigationBarHeight));
        //draw your image according to the coordinates of the navigation bar, i put it to the right top with a small right padding,
        //you have to play with coordinates according to your needs
        img.Draw(new CGRect(navigationBarWidth - navigationBarHeight - 30,//move 30px to the left (do not paste to right border :))
            0, navigationBarHeight, navigationBarHeight));
        UIImage backgroundImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        NavigationBar.SetBackgroundImage(backgroundImage, UIBarMetrics.Default);

        //bonus :) change your title color
        UINavigationBar.Appearance.SetTitleTextAttributes(new UITextAttributes()
        {
            TextColor = UIColor.White,
        });

        base.ViewDidLoad();
    }
}