[英]create bitmap to screen size keeping ratio
我正在嘗試制作牆紙應用程序。 而且在使用位圖設置牆紙時遇到了很大的麻煩。 我試圖找出答案一個星期。
我想將位圖設置為牆紙
我該怎么做? 我必須創建新的位圖嗎?
您需要調整圖片大小,以根據屏幕尺寸制作新的位圖。
這是代碼:
Bitmap bitmapOrg = BitmapFactory.decodeFile(getApplicationContext()
.getFilesDir().toString() + "/images/" + imagename);
Log.e("imageheight", "" + bitmapOrg.getHeight());
Log.e("imagewidth", "" + bitmapOrg.getWidth());
double imageheight = bitmapOrg.getHeight();
double imagewidth = bitmapOrg.getWidth();
DisplayMetrics metrics = getApplicationContext().getResources()
.getDisplayMetrics();
double screenwidth = metrics.widthPixels;
double sreeenheight = metrics.heightPixels;
Log.e("screennwidth", "" + screenwidth);
double newratio = screenwidth / imagewidth;
Log.e("newratio", "" + newratio);
double newratio1 = newratio * imageheight;
double newratio2 = newratio * (imagewidth - 10); // 10 margin in width
Log.e("newratio1", "" + newratio1);
int mainheight = (int) newratio1;
// int mainweidth = (int) imagewidth;
int mainweidth = (int) newratio2;
Log.e("Mainheight", "" + mainheight);
Log.e("Mainweidtht", "" + mainweidth);
// Here you will get the scaled bitmap
Bitmap new_ScaledBitmap = Bitmap.createScaledBitmap(bitmapOrg, mainweidth,mainheight, true);
// Use this bitmap as wallpaper
若要使位圖適合屏幕而不剪切任何內容,首先必須確定縱橫比是大於還是小於屏幕。 如果圖像的寬高比大於屏幕的高寬比,則表示位圖比屏幕高和/或不如屏幕寬,就像問題中的第二張圖像一樣。 因此,您應該像這樣根據高度縮放圖像:
if(imageWidth/imageHeight > screenWidth/screenHeight){
scaleFactor = screenHeight/imageHeight;
imageXPosition = screenWidth/2-imageWidth/2;
imageYPosition = 0;
否則,圖像應根據寬度進行縮放,如下所示:
}else{
scaleFactor = screenWidth/imageHeight;
imageXPosition = 0;
imageYPosition = screenWidth/2-imageWidth/2;
}
您可以使用這些值使用矩陣繪制位圖,也可以創建尺寸為imageWidth*scaleFactor
和imageHeight*scaleFactor
的比例位圖,並在imageXPosition
| imageYPosition
(這可以節省更多的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.