图片自动调整大小

Images automatically resized

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

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

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

I have read about density independent pixels on the android documentation and other websites, but can't seem to understand why the image dimensions would resize automatically.

问题出在[BitmapFactory.DecodeResource(Resources res,int id)](https://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeResource(android.content.res.Resources, int))。该方法依赖于密度。默认情况下,它将使用您 device/emulator 的密度。您正在使用两个不同密度的仿真器对其进行测试。所以这个方法创建了不同尺寸的位图。

解决方法: 为避免此问题,您应该使用此方法的其他版本:[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)) 其中 opts.Indensity 设置为固定值,例如:

var option = new BitmapFactory.Options();
option.InDensity = 320;
jp1 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon,option);
jp2 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon,option);
jp3 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon,option);
jp4 = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon,option);