簡體   English   中英

如何在Android中根據設備屏幕尺寸縮放位圖

[英]How to scale bitmaps based on device screen size in Android

我想創建與屏幕大小相關的圖像。 基本上我有一個縮放的位圖50w * 50h 我希望在小型設備上將其設置為50w * 50h ,在較大的設備上將其設置為稍大一點,以此類推。 我有一個dimen.xml文件,它針對不同的屏幕寬度使用不同的dp值。 但這似乎要求很高。 有沒有更簡單的方法可以做到這一點? 我已經做了一些研究,但沒有發現任何結果,有人可以幫忙嗎?

可能是這樣的

 public class BitmapScaler {
     // scale and keep aspect ratio
     public static Bitmap scaleToFitWidth(Bitmap b, int width) {
         float factor = width / (float) b.getWidth();
         return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
     }


     // scale and keep aspect ratio
     public static Bitmap scaleToFitHeight(Bitmap b, int height) {
        float factor = height / (float) b.getHeight();
         return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
     }


     // scale and keep aspect ratio
     public static Bitmap scaleToFill(Bitmap b, int width, int height) {
         float factorH = height / (float) b.getWidth();
         float factorW = width / (float) b.getWidth();
         float factorToUse = (factorH > factorW) ? factorW : factorH;
         return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse), 
         (int) (b.getHeight() * factorToUse), true);
      }


     // scale and don't keep aspect ratio
     public static Bitmap strechToFill(Bitmap b, int width, int height) {
         float factorH = height / (float) b.getHeight();
         float factorW = width / (float) b.getWidth();
         return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW), 
         (int) (b.getHeight() * factorH), true);
     }
 }

或者會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM