Drawable.createFromStream和getResources()。getDrawable,为什么它们的输出不同?

时间:2012-05-15 01:15:22

标签: java android

我有一张32x32的图像,我把它放在drawable文件夹中,并从服务器下载相同的图像应用程序。但下载的一个看起来更大(更像48x48)和像素化。

服务器代码(C#)

        MemoryStream tms = new MemoryStream();
        image.Save(tms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] imageData = tms.ToArray();
        //send data to phone

应用程序代码(Java)

    ByteArrayInputStream memStream = new ByteArrayInputStream(imageData);
    Drawable image = Drawable.createFromStream(memStream, ""); //big image and pixelated
    memStream.close();

但如果我从Resource加载相同的文件,它总是更小

Drawable image = getResources().getDrawable(R.drawable.image);

ImageView xml

<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:focusable="false"
    android:scaleType="center" />

编辑:

最后,设置BitmapDrawable的TargetDensity工作了!

Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0,
        imageData.length);
BitmapDrawable image = new BitmapDrawable(bmp);
image.setTargetDensity(bmp.getDensity());

1 个答案:

答案 0 :(得分:0)

根据设备的像素密度重新调整您的图像,尝试使用BitmapFactory.decodeStream(...)并使用new BitmapDrawable(Bitmap)进行包装,如果您需要Drawable对象。