How do I change the size of an image for a ToolbarItem

I have tried changing the actual image size of every SendMessage.png in my Xamarin Forms drawable folders yet the image renders the same. Can I programmatically change the icon in my xaml code below?

<ContentPage.ToolbarItems>
    <ToolbarItem
        Icon="SendMessage.png" 
        Text="Contact Us"
        Clicked="SendMessageClicked" />
    </ContentPage.ToolbarItems>

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    You have to implement it on each platform.
    The renderer on iOS:

    [assembly: ExportRenderer(typeof(MainPage), typeof(CustomPageRenderer))]
    namespace App.iOS
    {
        public class CustomPageRenderer : PageRenderer
        {
            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
                base.OnElementChanged(e);
            }
    
            public override void ViewWillAppear(bool animated)
            {
                base.ViewWillAppear(animated);
    
                UIViewController vc = NavigationController.TopViewController;
    
                List<UIBarButtonItem> items = new List<UIBarButtonItem>();
                int i = ((ContentPage)Element).ToolbarItems.Count - 1;
                foreach (UIBarButtonItem item in vc.NavigationItem.RightBarButtonItems)
                {
                    ToolbarItem toolBarItem = ((ContentPage)Element).ToolbarItems[i];
    
                    UIButton btn = new UIButton(UIButtonType.Custom);
                    btn.SetImage(item.Image, UIControlState.Normal);
                    btn.Frame = new CGRect(0, 0, 10, 10);
                    btn.TouchUpInside += (sender, args) => 
                    {
                        item.Target.PerformSelector(item.Action, null, 0.0);
                    };
    
                    UIBarButtonItem customItem = new UIBarButtonItem(btn);
                    customItem.CustomView.WidthAnchor.ConstraintEqualTo(10).Active = true;
                    customItem.CustomView.HeightAnchor.ConstraintEqualTo(10).Active = true;
                    items.Add(customItem);
    
                    i--;
                }
    
                vc.NavigationItem.RightBarButtonItems = items.ToArray();
            }
        }
    }
    

    On Android, you need to add this values in the styles.xml:

    <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
      <!--...-->  
    
      <item name="android:actionButtonStyle">@style/myActionButtonStyle</item>
      <item name="actionButtonStyle">@style/myActionButtonStyle</item>
    </style> 
    
    <style name="myActionButtonStyle" parent="Widget.AppCompat.ActionButton">
      <item name="android:minWidth">10dp</item>
      <item name="android:maxWidth">10dp</item>
      <item name="android:width">10dp</item>
    </style>
    
Sign In or Register to comment.