如何在创建位图之前测量 ImageView?

How to measure ImageView before creating bitmap into it?

我的 ImageView 在 x 轴上匹配屏幕尺寸,并且在我的布局中使用 在 y 轴上剩余 space。我想在此 ImageView 中创建与 ImageView 大小完全相同的位图。请问怎么做呢?可以通过一些自动设置来完成吗,我应该调用一些测量功能吗?

我试过 SetAdjustViewBounds() 但它对我不起作用。

创建足够大的位图(我不喜欢这样的内存浪费)并设置 SetScaleType(ImageView.ScaleType.Matrix) 有效,但是当我在 canvas,我不知道我应该绘制的区域的真实大小,canvas 和位图高度都等于 yScreen,而 imgWeekView 高度假装为 0,即使它绘制了整个区域所需区域为灰色。

imgWeekView = new ImageView(context);
//imgWeekView.SetAdjustViewBounds(true);
imgWeekView.SetScaleType(ImageView.ScaleType.Matrix);

layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent,1f);
layoutParams.Height = 0;
imgWeekView.LayoutParameters = layoutParams;

Bitmap bitmap = Bitmap.CreateBitmap((int)xScreen, (int)yScreen, Bitmap.Config.Argb8888);
cnvWeekView = new Canvas(bitmap);
imgWeekView.SetImageBitmap(bitmap);
linearLayout.AddView(imgWeekView); //whole activity layout

//Test
cnvWeekView.DrawColor(new Color(128, 128, 128));
Paint paint = new Paint(PaintFlags.AntiAlias);
paint.Color = new Color(255, 255,0);
cnvWeekView.DrawCircle(50, 50, 40, paint);

最后我找到了一种测量 ImageView 的方法,在这里我将 post 我的答案。

我认为应该有更简单的解决方案,但也许没有。从这个问题中我得到了大部分重要数据:

How to get the width and height of an android.widget.ImageView?

然而,在我的 android 应用程序中,情况看起来有点不同,我没有足够的经验来说明原因。我不得不稍微改变一下。我必须学习一些关于接口的知识,这个问题也有帮助。

Implementing the View.IOnTouchListener interface

以下是我的组合方式。首先,我创建了 class 来进行测量。

public class MyPredrawListener : Java.Lang.Object, ViewTreeObserver.IOnPreDrawListener
{
    ImageView imageView;
    public MyPredrawListener(ImageView img)
    {
        imageView = img;
    }
    public bool OnPreDraw()
    {
        imageView.ViewTreeObserver.RemoveOnPreDrawListener(this);
        int finalHeight = imageView.MeasuredHeight;
        int finalWidth = imageView.MeasuredWidth;
        Bitmap bitmap = Bitmap.CreateBitmap(finalWidth, finalHeight, Bitmap.Config.Argb8888);
        imageView.SetImageBitmap(bitmap);

        //Test to see result
        Canvas cnv = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.Color = new Color(255, 255, 0);
        cnv.DrawColor(new Color(128, 128, 128));
        cnv.DrawCircle(finalWidth-50, finalHeight-50, 50, paint);

        return true;
    }
}

在我创建 imageView 的代码中,我像这样设置监听器。

imgWeekView = new ImageView(context);
MyPredrawListener listener=new MyPredrawListener(imgWeekView);
imgWeekView.ViewTreeObserver.AddOnPreDrawListener(listener);

在 OnPreDraw 函数中,我放入测试代码以图形方式查看结果,将位图清除为灰色,并将黄色圆圈绘制到视图的右下角。