墙纸的位图调整大小setWallpaper

时间:2011-10-12 12:12:59

标签: android background bitmap scale wallpaper

我想为壁纸集缩放Bitmap但没有效果:|我有这个代码和原始文件夹和数组中的所有.jpg文件,代码:

baton3.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

        InputStream tapeta = getResources().openRawResource(textureArrayWin[n]);

        Bitmap bitmap = BitmapFactory.decodeStream(tapeta);
        Display display = getWindowManager().getDefaultDisplay(); 
        int width = display.getWidth();
        int height = display.getHeight();

        int oldwidth= bitmap.getWidth();
        int oldheight= bitmap.getHeight();
        float skalaszerokosci = ((float) oldwidth) / width;
        float skalawysokosci = ((float)oldheight) / height;

        Matrix macierz = new Matrix();
        macierz.postScale(skalaszerokosci, skalawysokosci);

        Bitmap zmieniona = Bitmap.createBitmap(bitmap, 0, 0, 
                width, height, macierz, true); 


        try
        {

            getApplicationContext().setWallpaper(zmieniona);


        }
        catch(IOException e)
        {
            e.printStackTrace();
        }


    }

});

2 个答案:

答案 0 :(得分:1)

添加到清单 <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/> <uses-permission android:name="android.permission.SET_WALLPAPER" />

答案 1 :(得分:1)

以下是代码:

    // Get display dimensions
    final DisplayMetrics metrics = getResources().getDisplayMetrics();
    final int displayWidth = metrics.widthPixels;
    final int displayHeight = metrics.heightPixels;

    // Here I'm decoding a resource, just for the example sake
    final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);

    // obtain the original Bitmap's dimensions
    final int originalWidth = bitmap.getWidth();
    final int originalHeight = bitmap.getHeight();

    // Obtain the horizontal and vertical scale factors
    final float horizontalScaleFactor = (float) originalWidth / (float) displayWidth;
    final float verticalScaleFactor = (float) originalHeight / (float) displayHeight;

    // Get the biggest scale factor to use in order to maintain original image's aspect ratio 
    final float scaleFactor = Math.max(verticalScaleFactor, horizontalScaleFactor);
    final int finalWidth = (int) (originalWidth / scaleFactor);
    final int finalHeight = (int) (originalHeight / scaleFactor);

     // Create the final bitmap
    final Bitmap wallpaperBmp = Bitmap.createScaledBitmap(
            bitmap, finalWidth, finalHeight, true);

    // Recycle the original bitmap
    bitmap.recycle();

    // Finally set it as wallpaper
    try {
        final WallpaperManager wallMan = WallpaperManager.getInstance(this);
        wallMan.setBitmap(wallpaperBmp);
    } catch (IOException e) {
        Log.e("Wallpaper", "Something went wrong: " + e.toString());
        wallpaperBmp.recycle();
    }

另外,不要忘记将SET_WALLPAPER添加到manifest.xml:

<uses-permission android:name="android.permission.SET_WALLPAPER"/>