繁体   English   中英

创建位图与屏幕尺寸的保持比例

[英]create bitmap to screen size keeping ratio

将original_Bitmap转换为new_Bitmap

我正在尝试制作墙纸应用程序。 而且在使用位图设置墙纸时遇到了很大的麻烦。 我试图找出答案一个星期。

我想将位图设置为墙纸

  1. 避免作物
  2. scaleType:fit_center(垂直对齐中心,保持原始位图的比例)

我该怎么做? 我必须创建新的位图吗?

您需要调整图片大小,以根据屏幕尺寸制作新的位图。

这是代码:

        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*scaleFactorimageHeight*scaleFactor的比例位图,并在imageXPosition | imageYPosition (这可以节省更多的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM