2016-06-28 83 views
-1

我需要顯示其存儲在數據庫中的圖像和我在與圖像(位圖)寬度/高度和ImageView的問題...Bitmap和ImageView的問題 - 問題圖像寬度/高度

只是爲了測試 - 當我在項目的可繪製添加相同的圖像,我可以用這個:

作品:

Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.menu_image); 
BitmapDrawable bd = new BitmapDrawable(context.getResources(), b); 
imageView.setImageDrawable(bd); 

一樣

imageView.setImageResource(R.drawable.menu_image); 

這以下不工作因爲圖像沒有被調整大小:

public static Bitmap base64ToBitmap(String b64) { 
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT); 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inDensity =  context.getResources().getDisplayMetrics().densityDpi; 
    options.inTargetDensity = context.getResources().getDisplayMetrics().densityDpi; 
    Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length, options); 
    return bitmap; 
} 
:在哪裏使用該構建的圖像

imageView.setImageBitmap(image); 

相同

imageView.setImageDrawable(new BitmapDrawable(context.getResources(), image)); 

圖片原始尺寸爲338x94。

676x188,這是從項目的drawables目錄中使用圖像時的圖像大小。這是我正在尋找的大小,在這種情況下。我想快速修復會使用Bitmap.createScaledBitmap(),但我有幾個不同的圖像格式,我想使用imageView.setImageBitmap或imageView.setImageDrawable行爲像我從項目的drawables目錄中加載的位圖。

回答

-1

使用來自github

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); 
    } 
    } 
以下輔助類