gpt4 book ai didi

c# - 如何在 Xamarin iOS 中将图标从 UIBarButtonSystemItem 转换为 UIImage

转载 作者:行者123 更新时间:2023-11-29 05:59:21 26 4
gpt4 key购买 nike

我正在尝试从 UIBarButtonSystemItem like UIBarButtonSystemItem.Camera 类型转换图标到 UIImage 中。用户可以在Swift and ObjC中做到这一点,但我无法弄清楚。

当我按照 Swift 和 ObjC 教程中的说明进行操作时,我的代码中出现空引用异常错误

{
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;
}

在 StackOverflow 中找不到 C# 的任何内容。以前有人尝试过吗?

最佳答案

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;
}

来自 Xamarin iOS Gitter 的 @DaleXSoto 提供的解决方案

“问题是您正在将选择器( View )调用到 tempItem 对象中但这是一个黑客,因为 UIBarButtonItem 响应 View 只是因为有人发现了嘿,它不在标题上

因此,执行 IntPtr_objc_msgSend 就是您在 tempItem 对象上调用 View 的方式”

关于c# - 如何在 Xamarin iOS 中将图标从 UIBarButtonSystemItem 转换为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com