Skip to content

Instantly share code, notes, and snippets.

@saamerm
Last active February 23, 2019 00:10
Show Gist options
  • Save saamerm/bf35c8a7c945fedc3cd64f21b8ea5a54 to your computer and use it in GitHub Desktop.
Save saamerm/bf35c8a7c945fedc3cd64f21b8ea5a54 to your computer and use it in GitHub Desktop.
Trial at Converting UIBarButtonSystemItem to UIImage in Xamarin.iOS C#
// Solution provided by @dalexsoto from https://gitter.im/xamarin/xamarin-macios
[DllImport (Constants.ObjectiveCLibrary, EntryPoint = "objc_msgSend")]
public extern static IntPtr IntPtr_objc_msgSend (IntPtr receiver, IntPtr selector);
public static UIImage GetImage (UIBarButtonSystemItem systemItem)
{
var tempItem = new UIBarButtonItem (systemItem);
// Add to toolbar and render it
var bar = new UIToolbar ();
bar.SetItems (new [] { tempItem }, false);
bar.SnapshotView (true);
// Get image from real UIButton
var selHandle = Selector.GetHandle ("view");
var itemView = Runtime.GetNSObject<UIView> (IntPtr_objc_msgSend (tempItem.Handle, selHandle));
foreach (var view in itemView?.Subviews) {
if (view is UIButton button)
return button.ImageForState (UIControlState.Normal);
}
return null;
}
// Unsuccessful trials
// Tried to use icons from https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/system-icons/
public static UIImage ToUIImage(UIBarButtonSystemItem item, UIViewController viewController)
{
UIImage image = null;
viewController.InvokeOnMainThread(() =>
{
UIBarButtonItem oldItem = viewController.NavigationItem.RightBarButtonItem;
var buttonItem = new UIBarButtonItem(item);
// Add to toolbar and render it
viewController.NavigationItem.RightBarButtonItem = buttonItem;
var x = new ObjCRuntime.Selector("view");
var y = viewController.NavigationItem.RightBarButtonItem.PerformSelector(x);
UIView itemView = (UIView)y;
// Get the image from real UIButton
foreach (var view in itemView.Subviews)
{
if (view.GetType() == typeof(UIButton))
image = ((UIButton)view).ImageView.Image;
}
viewController.NavigationItem.RightBarButtonItem = oldItem;
});
return image;
}
public static UIImage ToUIImage2(UIBarButtonSystemItem item, UIViewController viewController)
{
UIImage image = null;
viewController.InvokeOnMainThread(() =>
{
var buttonItem = new UIBarButtonItem(item);
// Add to toolbar and render it
var tempItem = new UIBarButtonItem[1] { buttonItem };
var bar = new UIToolbar();
bar.SetItems(tempItem, false);
bar.SnapshotView(true);
// Get the image from real UIButton
var buttonItemView = bar.ValueForKey(new Foundation.NSString("view"));
var itemView = (UIView)buttonItemView;
foreach (var view in itemView.Subviews)
{
if (view.GetType() == typeof(UIButton))
image = ((UIButton)view).ImageView.Image;
}
});
return image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment