图像会自动调整大小

时间:2018-01-19 23:48:22

标签: android xamarin.android android-canvas android-drawable autoresize

使用Xamarin编程android,我有一些 32x32 像素尺寸的图像,我需要在canvas上显示。我一直在使用带有xhdpi屏幕的Android SDK模拟器测试代码,图像似乎会自动调整大小以使其尺寸加倍。即它们变为 64像素宽,64像素高。然后,我创建了另一个带有mdpi屏幕的AVD,图像似乎是正确的大小。

我已经阅读了android documentation和其他网站上与密度无关的像素,但似乎无法理解为什么图像尺寸会自动调整大小。幕后是否有隐含的大小调整?如果是这样,为什么Android开发人员不会在他们的文档中提到它?还有什么我需要设置的吗?下面是代码的相关部分(我调整大小的图像是 jp1 jp2 等):

    Paint bkgBmpPaint = new Paint(); Color myColor = new Color(); 
    Paint myTextPaint = new Paint();
    private int a = 0, b = 0, bw = 0; 
            private Bitmap partialBitmap = null;
            DisplayMetrics dm = new DisplayMetrics();
            private Bitmap jp1,jp2,jp3,jp4;

            public MyCanvasPath(Context context) : base(context) //constructor
            {
    partialBitmap = Bitmap.CreateBitmap(Resources.Configuration.ScreenWidthDp, Resources.Configuration.ScreenHeightDp,Bitmap.Config.Argb8888);
                float scale = Resources.DisplayMetrics.Density;
    jp1 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.jp1);
    jp2 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.jp2);
    jp3 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.jp3);
    jp4 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.jp4);

                Canvas myCanvas = new Canvas(partialBitmap); b = myCanvas.Height; a = myCanvas.Width; bw = jp1.Width;
                IList<Bitmap> pImgList = new List<Bitmap> {
                 jp1, jp2, jp3, jp4  };
                imgCount = pImgList.Count;
                    for (int x = 0; x < imgCount; x++)
                    {
                        myCanvas.DrawBitmap(pBmpList.ElementAt(x), bw * x, 0, null);
                    }}
protected override void OnDraw(Canvas screenCanvas)
        {
            screenCanvas.DrawBitmap(partialBitmap, 0, 0, null);
            partialBitmap.Recycle();
        }

1 个答案:

答案 0 :(得分:1)

  

我已经在Android文档和其他网站上阅读了关于密度无关的像素,但似乎无法理解为什么图像尺寸会自动调整大小。

问题在于[BitmapFactory.DecodeResource(Resources res,int id)](https://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeResource(android.content.res.Resources,int))。该方法取决于密度。默认情况下,它将使用您的设备/模拟器的密度。您正在使用两个具有不同密度的仿真器对其进行测试。因此,此方法创建具有不同维度的位图。

解决方案: 为了避免这个问题,你应该使用这个方法的其他版本:[decodeResource(Resources res,int id,BitmapFactory.Options opts)](https://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeResource(android.content.res.Resources,int,android.graphics.BitmapFactory.Options))with {{ 1}}设置为固定值,例如:

opts.Indensity
相关问题