我正在尝试在 Xamarin.Android
平台上获取屏幕截图。
public static Android.Content.Context Context { get; private set; }
public override View OnCreateView(View parent, string name, Context context, IAttributeSet attrs)
{
MainActivity.Context = context;
return base.OnCreateView(parent, name, context, attrs);
}
我试图找出为什么以下 rootView.Width
和 Height
始终返回 0。
var rootView = ((Activity)MainActivity.Context).Window.DecorView.RootView;
Console.WriteLine ("{0}x{1}", rootView.Width,rootView.Height);
我的最终目标是将 View 的屏幕截图捕获为图像并生成 pdf。
最佳答案
我不知道 Xamarin,但对于此解决方案,它似乎与原生 Android 相同。
调用 onCreateView() 时,尚未测量 View 。要获取 View 尺寸,您应该附加一个特定的监听器:onLayoutChangeListener
。
这是一个 Android native 代码示例:
rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
int oldRight, int oldBottom) {
int width = right - left;
int height = bottom - top;
v.removeOnLayoutChangeListener(this); // Remove the listener
}
});
你可以找到here用于 Xamarin 的监听器
希望对您有所帮助! :)
关于android - Xamarin.Android 中的 rootView 高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33111575/