How to have dynamic image on Xamarin Form Header? - xamarin

I am working on Xamarin form in which header title will have weather temperature and weather icon on its right side.
For example
New York 60' F SunnyIcon
I am using openweather api to fetch the data.
Problem is, I am not able to create a dynamic image holder on the Xamarin Form Header.
How to have a dynamic image on the Xamarin Form Header?
Attached is a sample app which i am working on based on source code which i downloaded from github ...

I'm not sure what you mean by "Header," but if you're trying to add an icon to the Navigation Bar, you can do that by calling ToolbarItems.add() in the constructor of your page like this:
public myPage()
{
InitializeComponent();
ToolbarItems.Add(new ToolbarItem("Weather", "WeatherIcon.png", async () =>
{
//Code to Execute when Icon is tapped
}));
}
When adding the ToolbarItem, the first parameter is the name of the item, the second is the name of the image that will be displayed at the end of the Navigation bar, and the last one is optional which creates a method that is executed when the icon is tapped.
If you need the icon to be different depending on the current weather, you can do that like this:
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));
}

You have to write a custom renderer like this: and the result:
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();
}
}

Related

Xamarin iOS ToolbarItem Image showing white image

Xamarin Forms IconImageSource:
On Android Toolbar image is shown correctly, on iOS a white image is shown. How can I fix this?
I added file to Resources folder and set build Action to BundleResource.
If I change filename to non excisting file, image is not shown at all. I tried changing extension to JPG, same result, also a white image is shown.
I used this code snippit.
ToolbarItem toolbarItemSearch = new ToolbarItem { IconImageSource = ImageSource.FromFile("searchIcon.png") };
ToolbarItems.Add(toolbarItemSearch);
iOS has tinting the ToolbarItems by default , the color is blue/white .
To solve it we need to create a custom renderer for NavigationPage , and set the TintColor to transparent , and set the image with another rendering mode .
Sample code
[assembly: ExportRenderer(typeof(NavigationPage), typeof(MyRenderer))]
namespace FormsApp.iOS
{
class MyRenderer : NavigationRenderer
{
public override void PushViewController(UIViewController viewController, bool animated)
{
base.PushViewController(viewController, animated);
var currentPage = (this.Element as Xamarin.Forms.NavigationPage)?.CurrentPage;
if (this.NavigationBar == null || currentPage == null)
return;
var buttonItems = TopViewController.NavigationItem.RightBarButtonItems;
foreach (var button in buttonItems)
{
if(button.Image != null){
button.Image = button.Image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
button.TintColor = UIColor.Clear;
}
}
}
}
}
Refer to
Image in Toolbar item on iOS are white(Xamarin Forms)
The solution from #ColeX - MSFT did the trick! Additionally make sure to do a null pointer check for non Image buttons.

How to load image onto a button in xamarin forms PCL?

I am picking a photo from photo library and i get the following
AlbumPath:
assets-library://asset/asset.JPG?id=106E99A1-4F6A-45A2-B320-B0AD4A8E8473&ext=JPG
Path:
/Users/myname/Library/Developer/CoreSimulator/Devices/21CB035B-A738-4F74-B121-2DB2A6B5372A/data/Containers/Data/Application/3081A323-98AF-4EF6-95B9-29D4C2CD8425/Documents/temp/IMG_20170408_111143.jpg
How do i assign this image to a button ? I tried the following.
var file = await CrossMedia.Current.PickPhotoAsync(
new Plugin.Media.Abstractions.PickMediaOptions
{
});
Button btn = new Button();
btn.Image = (Xamarin.Forms.FileImageSource)ImageSource.FromFile(file.Path);
No image is displayed on the button. Any help help is appreciated.
Thank you.
Once you deploy the application the app will not have access to your mac. For the application to use the picture it will need to be a bundled resource within the iOS application. Below is a simple example of using images within an iOS app. You'll definitely want to consider just adding a gesture listener to your image instead of making it a button though. If you try to just use the image on a button you'll have to do some styling adjustments to get it to look clean.
Image Setup
Put image in iOS Resource folder
Make sure bundledresource is selected from image properties.
Image Button
public class ImageButton : ContentPage
{
private Button _imageBtn = new Button { Image = "icon.png", Text = "Sample button" };
public ImageButton()
{
Content = new StackLayout
{
Children =
{
_imageBtn
}
};
}
}
Image with TapGesture
public class ImageButton : ContentPage
{
private Image _imageBtn = new Image { Source = "icon.png" };
private TapGestureRecognizer _imageTap = new TapGestureRecognizer();
public ImageButton()
{
_imageBtn.GestureRecognizers.Add(_imageTap);
Content = new StackLayout
{
Children =
{
_imageBtn
}
};
_imageTap.Tapped += (s, e) =>
{
// handle the tap
};
}
}

How to identify user tapped on Editor field in Xamarin forms?

First thing, I have an Editor.I can Identify if the user entered any text in that Edior.But i need to return something when the user tapped on the Editor. How to achieve this?
var msgEditor = new Editor
{
Margin = new Thickness(10, 0, 10, 0),
HeightRequest = App.ScreenHeight,
};
Secong thing, Editor is inside the scrollview.When i tapped on the Editor scrollview scrolls down.I need to manually pull down to see the cursor.How to set content offset when i tapped on Editor?
ScrollView scroll = new ScrollView
{
Content = msgEditor,
};
Content = scroll;
On the editor, you have the focus event that notifies you that the user tapped the editor. You can do as follow :
{
var editor = new Editor();
editor.Focused += EditorOnFocused;
}
private void EditorOnFocused(object sender, FocusEventArgs focusEventArgs)
{
//do your stuff
}

How to show ActivityIndicator in the middle of the screen?

I've created an activity indicator and added it to StackLayout and when I make it running, in the emulator it shows in the top right corner Android 4.4 and in iOS no show and in Android 6 phone, it don't show.
var indicator = new ActivityIndicator()
{
Color = Color.Blue,
};
indicator.SetBinding(ActivityIndicator.IsVisibleProperty, "IsBusy", BindingMode.OneWay);
indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsBusy", BindingMode.OneWay);
AbsoluteLayout.SetLayoutFlags(indicator, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(indicator, new Rectangle(0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));
mainLayout.Children.Add(indicator);
I want to show the activity indicator to the center of the screen because the operation takes time to complete.
The indicator that you are seeing in the status bar is the default behavior of the IsBusy property of the base page class. The reason your code isn't working is because you are attempting to bind visibility of your ActivityIndicator to that property - but you aren't specifying a binding source. If you look in your debugger's application output log then you will probably see messages along the lines of "Property 'IsBusy' not found on type 'Object'".
To fix it, you simply need to point the Binding Context of each binding to the form. Give this a try:
public partial class App : Application
{
public App ()
{
var mainLayout = new AbsoluteLayout ();
MainPage = new ContentPage {
Content = mainLayout
};
var containerPage = Application.Current.MainPage;
var indicator = new ActivityIndicator() {
Color = Color.Blue,
};
indicator.SetBinding(VisualElement.IsVisibleProperty, new Binding("IsBusy", BindingMode.OneWay, source: containerPage));
indicator.SetBinding(ActivityIndicator.IsRunningProperty, new Binding("IsBusy", BindingMode.OneWay, source: containerPage));
AbsoluteLayout.SetLayoutFlags(indicator, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(indicator, new Rectangle(0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));
mainLayout.Children.Add(indicator);
containerPage.IsBusy = true;
}
}
You add your activity indicator to stack layout, but you are setting Absolute layout LayoutFlags, they won't work.
to be able to achieve what you want, you need suck structure
AbsoluteLayout
StackLayout
ActivityIndicator
mainLayout should be AbsoluteLayout, all content should be contained in nested StackLayout.

Background image with Carousel effect

I would like to create a layout with a fullscreen background image and some UI elements on top of it. The twist is this:
I would like the background image to swipeable like a carousel, but I would like the UI elements to stay in place. That is if I swipe the screen, the background image should slide to the side and a new image should replace it. I know about CarouselPage, but it seems to me that it won't do the trick, since a Page can have only one child which it replaces on swipe, meaning that the UI elements would be descendants of the CarouselPage and therefore would also be animated.
I am guessing I need some sort of custom renderer here, but how should I go about designing it? Should it be one fullscreen Image control replaced be another fullscreen Image control with the UI elements on top of it? And how can I do this? Or is there an all together better approach?
I am developing for iOS and Android using Xamarin.Forms.
Thanks in advance.
I don't like repeating myself much, and I think that multiple layers of actionable items can lead to confusion, but the problems appeals to me and I can see a niche for this kind of UI, so here's my take on your question.
Let's assume this is the (Xamarin.Forms.)Page you want to render with a custom carousel background:
public class FunkyPage : ContentPage
{
public IList<string> ImagePaths { get; set; }
public FunkyPage ()
{
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center,
Spacing = 12,
Children = {
new Label { Text = "Foo" },
new Label { Text = "Bar" },
new Label { Text = "Baz" },
new Label { Text = "Qux" },
}
};
ImagePaths = new List<string> { "red.png", "green.png", "blue.png", "orange.png" };
}
}
The renderer for iOS could look like this:
[assembly: ExportRenderer (typeof (FunkyPage), typeof (FunkyPageRenderer))]
public class FunkyPageRenderer : PageRenderer
{
UIScrollView bgCarousel = new UIScrollView (RectangleF.Empty) {
PagingEnabled = true,
ScrollEnabled=true
};
List<UIImageView> uiimages = new List<UIImageView> ();
protected override void OnElementChanged (VisualElementChangedEventArgs e)
{
foreach (var sub in uiimages)
sub.RemoveFromSuperview ();
uiimages.Clear ();
if (e.NewElement != null) {
var page = e.NewElement as FunkyPage;
foreach (var image in page.ImagePaths) {
var uiimage = new UIImageView (new UIImage (image));
bgCarousel.Add (uiimage);
uiimages.Add (uiimage);
}
}
base.OnElementChanged (e);
}
public override void ViewDidLoad ()
{
Add (bgCarousel);
base.ViewDidLoad ();
}
public override void ViewWillLayoutSubviews ()
{
base.ViewWillLayoutSubviews ();
bgCarousel.Frame = View.Frame;
var origin = 0f;
foreach (var image in uiimages) {
image.Frame = new RectangleF (origin, 0, View.Frame.Width, View.Frame.Height);
origin += View.Frame.Width;
}
bgCarousel.ContentSize = new SizeF (origin, View.Frame.Height);
}
}
This was tested and works. Adding a UIPageControl (the dots) is easy on top of this. Autoscrolling of the background is trivial too.
The process is similar on Android, the overrides are a bit different.

Resources