Bitmap.createScaledBitmap不会缩放到屏幕大小

时间:2014-08-07 15:42:59

标签: android bitmap

使用createScaledBitmap遇到一些问题。它不适合我的屏幕尺寸,我仍然有左右空间。

为什么这段代码

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    Resources res = getResources();

    Bitmap source = BitmapFactory.decodeResource(res, R.drawable.red);
    Bitmap overlay = Bitmap.createScaledBitmap(source, width, height, false);

导致此屏幕:

enter image description here

有什么想法吗?提前谢谢!

4 个答案:

答案 0 :(得分:1)

您的位图实际上比您的ImageView更大,因为它的屏幕大小而不是视图的大小,这意味着正在强制执行ImageView比例类型并缩小您的位图。在视图中以XML格式或在代码中将缩放类型设置为Matrix。因为Matrix默认设置为单位矩阵,所以不执行任何缩放。

答案 1 :(得分:0)

您可以在任何活动中使用以下代码来获取屏幕尺寸:

    public static int displayWidth,displayHeight;



    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    displayWidth = dm.widthPixels;
    displayHeight = dm.heightPixels;

并将displayWidth和height变量传递给

  

Bitmap.createScaledBitmap

方法

答案 2 :(得分:0)

尝试此解码位图:

其中imagefilepath是图像的路径名,它将在String中隐藏,使用

转换为File

File photos= new File(imageFilePath); 照片是图像的文件名,现在您可以根据需要设置高度和宽度。

Bitmap bitmap = decodeFile(photo);
            bitmap = Bitmap.createScaledBitmap(bitmap,150, 150, true);
            imageView.setImageBitmap(bitmap);

    private Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);              
        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale++;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

答案 3 :(得分:0)

我不确定,但也许是因为你不考虑动作栏高度

试试这段代码

    //this for getting actionbar height
    TypedValue tv = new TypedValue();
    int actionBarHeight = 0;
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
    {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    }
    ////////
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    //
    int height = size.y - actionBarHeight;

    Resources res = getResources();

    Bitmap source = BitmapFactory.decodeResource(res, R.drawable.red);
    Bitmap overlay = Bitmap.createScaledBitmap(source, width, height, false);
相关问题