閱讀870 返回首頁    go 阿裏雲 go 技術社區[雲棲]


android圖片的縮放

 
import android.app.Activity;   
  1. import android.graphics.Bitmap;   
  2. import android.graphics.BitmapFactory;   
  3. import android.graphics.Matrix;   
  4. import android.graphics.drawable.BitmapDrawable;   
  5. import android.os.Bundle;   
  6. import android.view.ViewGroup.LayoutParams;   
  7. import android.widget.ImageView;   
  8. import android.widget.LinearLayout;   
  9. import android.widget.ImageView.ScaleType;   
  10.   
  11. public class bitmaptest extends Activity {   
  12. public void onCreate(Bundle icicle) {   
  13.         super.onCreate(icicle);   
  14.         setTitle("eoeAndroid教程: 縮放和旋轉圖片 -by:IceskYsl");   
  15.         LinearLayout linLayout = new LinearLayout(this);   
  16.   
  17.         // 加載需要操作的圖片,這裏是eoeAndroid的logo圖片   
  18.         Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),   
  19.                R.drawable.eoe_android);   
  20.   
  21.         //獲取這個圖片的寬和高   
  22.         int width = bitmapOrg.getWidth();   
  23.         int height = bitmapOrg.getHeight();   
  24.   
  25.         //定義預轉換成的圖片的寬度和高度   
  26.         int newWidth = 200;   
  27.         int newHeight = 200;   
  28.   
  29.         //計算縮放率,新尺寸除原始尺寸   
  30.         float scaleWidth = ((float) newWidth) / width;   
  31.         float scaleHeight = ((float) newHeight) / height;   
  32.   
  33.         // 創建操作圖片用的matrix對象   
  34.         Matrix matrix = new Matrix();   
  35.   
  36.         // 縮放圖片動作   
  37.         matrix.postScale(scaleWidth, scaleHeight);   
  38.   
  39.         //旋轉圖片 動作   
  40.         matrix.postRotate(45);   
  41.   
  42.         // 創建新的圖片   
  43.         Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 00,   
  44.                           width, height, matrix, true);   
  45.   
  46.         //將上麵創建的Bitmap轉換成Drawable對象,使得其可以使用在ImageView, ImageButton中   
  47.         BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);   
  48.   
  49.         //創建一個ImageView   
  50.         ImageView imageView = new ImageView(this);   
  51.   
  52.         // 設置ImageView的圖片為上麵轉換的圖片   
  53.         imageView.setImageDrawable(bmd);   
  54.   
  55.         //將圖片居中顯示   
  56.         imageView.setScaleType(ScaleType.CENTER);   
  57.   
  58.         //將ImageView添加到布局模板中   
  59.         linLayout.addView(imageView,   
  60.           new LinearLayout.LayoutParams(   
  61.                       LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT   
  62.                 )   
  63.         );   
  64.   
  65.         // 設置為本activity的模板   
  66.         setContentView(linLayout);   
  67.     }   
  68. }   

最後更新:2017-04-02 06:51:46

  上一篇:go Action Bar示例代碼 (一)
  下一篇:go HttpClient連接請求超時設置