【问题标题】:rootView Height and Width in Xamarin.AndroidXamarin.Android 中的 rootView 高度和宽度
【发布时间】:2015-10-13 20:01:36
【问题描述】:

我正在尝试在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.WidthHeight 总是返回0。

var rootView = ((Activity)MainActivity.Context).Window.DecorView.RootView;
Console.WriteLine ("{0}x{1}", rootView.Width,rootView.Height);

我的最终目标是将视图的屏幕截图捕获为图像并生成 pdf。

【问题讨论】:

    标签: android xamarin


    【解决方案1】:

    我不知道 Xamarin,但是对于此解决方案,它似乎与原生 Android 相同。

    当 onCreateView() 被调用时,视图还没有被测量。要获得视图尺寸,您应该附加特定的侦听器:onLayoutChangeListener

    这是一个 Android 原生代码示例:

    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 的侦听器

    希望它的帮助! :)

    【讨论】:

      【解决方案2】:

      在 onCreateView 中,对象的宽度和高度尚未定义。它们是在活动生命周期的后期阶段定义的。

      您必须为此使用 treeviewobserver。

      以您的根视图为例:

      rootView.ViewTreeObserver.GlobalLayout += (object sender, EventArgs e) => {
            Console.WriteLine ("{0}x{1}", rootView.Width,rootView.Height);
      };
      

      在该方法中,宽度和高度将是已知的。

      另外,你想给你的rootview拍照,最好的方法是使用这个方法,它会自动输出一个视图的Bitmap到变量b。

      rootView.DrawingCacheEnabled = true;
      Bitmap b = rootView.GetDrawingCache(true);
      

      希望这能让您顺利上路!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        相关资源
        最近更新 更多