Java 创建位图与屏幕大小保持比率
我正在尝试制作一个壁纸应用程序。我在用位图设置壁纸时遇到了很大的麻烦。我已经试着找出答案一个星期了 我想把位图设置成壁纸Java 创建位图与屏幕大小保持比率,java,android,bitmap,android-wallpaper,Java,Android,Bitmap,Android Wallpaper,我正在尝试制作一个壁纸应用程序。我在用位图设置壁纸时遇到了很大的麻烦。我已经试着找出答案一个星期了 我想把位图设置成壁纸 避免收割 scaleType:fit_center(将中心垂直对齐,保持原始位图的比例) 我怎样才能做到?我必须创建新位图吗?您需要根据屏幕大小调整图片大小以创建新位图 代码如下: Bitmap bitmapOrg = BitmapFactory.decodeFile(getApplicationContext() .getFi
我怎样才能做到?我必须创建新位图吗?您需要根据屏幕大小调整图片大小以创建新位图 代码如下:
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;
}
否则,应根据宽度缩放图像,如下所示:
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
(这更节省内存。那么您希望位图填充整个屏幕,还是不要像上面的图像那样被裁剪?@Gumbo不要像上面的图像那样被裁剪!!