如何在Xamarin Form Header上显示动态图像?
问题描述:
我正在使用Xamarin格式,其中标题标题右侧会显示天气温度和天气图标。如何在Xamarin Form Header上显示动态图像?
例如
纽约60' F SunnyIcon
我使用openweather API来获取数据。
问题是,我无法在Xamarin表格页眉上创建动态图像保存器。
如何在Xamarin表格页眉上显示动态图像?
附上对此我根据我从GitHub下载源代码工作的一个示例应用程序...
答
我不知道你的意思是“头”,但如果
public myPage()
{
InitializeComponent();
ToolbarItems.Add(new ToolbarItem("Weather", "WeatherIcon.png", async() =>
{
//Code to Execute when Icon is tapped
}));
}
当添加ToolbarItem
,第一PARAMET:你想添加一个图标到Navigation Bar
,您可以在您的网页这样的构造函数调用ToolbarItems.add()
做er是项目的名称,第二个是将在导航栏末尾显示的图像的名称,最后一个是可选的,它会创建一个在轻击图标时执行的方法。
如果您需要的图标是根据当前的天气不同,可以是这样做的:
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));
}
答
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();
}
}
+0
谢谢..我会尝试并将更新你.. – goofyui
你是什么意思的“标题”?导航栏?或者是其他东西?标题在XF中没有任何特定的含义。 – Jason
@jason,是的,我提到关于导航栏。 – goofyui
@Jason,我已附上我的示例应用程序的屏幕截图..其中你可以看到天气图标在温度场..,我需要显示该图标以及城市名称,温度后跟图标 – goofyui