Android WallpaperManager setBitmap fitCenter

时间:2017-07-03 14:44:08

标签: android image bitmap image-resizing

我试图使用WallpaperManager将位图设置为我手机壁纸的中心位置。

  • 图片大小:3840 x 2160
  • 手机尺寸:1080 x 1920

我尝试了很多策略:

  1. myWallpaperManager.suggestDesiredDimensions(width,height);
  2. Bitmap.createScaledBitmap(mImage,width,height,true);
  3. Set Wallpaper with bitmap avoid crop and set fit center
  4. how to fit the whole image on screen as wallpaper
  5. Wallpaper not properly fit on device screen
  6. https://developer.android.com/reference/android/app/WallpaperManager.html
  7. http://androidexample.com/How_to_Set_WallPaper_in_Android/question_answer.php?view=qad&token=39
  8. 每当我得到一个不适合居中的奇怪位图时,是否有人有任何建议?

    我希望它看起来像什么: enter image description here

    图片信息: enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了答案:Scaled Bitmap maintaining aspect ratio

我做的是:

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int phoneHeight = metrics.heightPixels;
    int phoneWidth = metrics.widthPixels;

    Bitmap mBit = returnBitmap(mImage, phoneWidth, phoneHeight);

private Bitmap returnBitmap(Bitmap originalImage, int width, int height){
    Bitmap background = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888);

    float originalWidth = originalImage.getWidth();
    float originalHeight = originalImage.getHeight();

    Canvas canvas = new Canvas(background);

    float scale = width / originalWidth;

    float xTranslation = 0.0f;
    float yTranslation = (height - originalHeight * scale) / 2.0f;

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);

    canvas.drawBitmap(originalImage, transformation, paint);

    return background;
}