1、Android 圖片加載過大導致內存溢出解決辦法
public void loadImage(){
//取得手機窗體的寬高
WindowManager wm = this.getWind
owManager();
int screenWidth = wm.getDefaultDisplay().getWidth();
int screenHeight = wm.getDefaultDisplay().getHeight();
//通過圖片文件的信息,得到圖片的寬高
BitmapFactory.Options options = new Options();//解析位圖附加條件
options.inJustDecodeBounds = true; //不去解析圖像,只得到圖像的文件信息
Bitmap bitmap = BitmapFactory.decodeFile("File path",options);
//得到圖片寬高
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
//計算縮放比
int scaleWidth = imageWidth / screenWidth;
int scaleHeight = imageHeight / screenHeight;
//取得合適縮放比
int scale = 1;
if(scaleWidth > scaleHeight && scaleHeight > 1){
scale = scaleWidth;
}
if(scaleHeight > scaleWidth && scaleWidth > 1){
scale = scaleHeight;
}
//加載真是圖片
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile("File Path", options);
//將圖片顯示在你要顯示的控件上
//建議使用WeakReference代替強引用
}
2.拷貝圖片
public void copyImage(){
//導入位圖
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_lock_idle_alarm);
//創建一個圖形的副本,此時的這個副本是空白的
Bitmap alterBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
//準備一個畫板,在上面放上準備好的空白的位圖
Canvas canvas = new Canvas();
//準備一個畫筆
Paint paint = new Paint();
paint.setColor(Color.WHITE);
//畫圖
Matrix m = new Matrix();
canvas.drawBitmap(bitmap,m,paint);
}
3、圖形的縮放
//圖形縮放函數(行列式)
Matrix matrix = new Matrix();
matrix.setValues(new float[] {
1, 0, 0,
0, 1, 0,
0, 0, 1
});
x = 1x + 0y + 0z
y = 0x + 1y + 0z
z = 0x + 0y + 1z
通過canvas.drawBitmap(bmp, matrix, paint);
創建bitmap;
(1)水平縮放0.5
(2)垂直拉扯2倍
matrix.setScale(1.5f,1);//水平點放大到1.5f,垂直1
4、圖形的旋轉
Matrix matrix = new Matrix();
matrix.setRotate(15);
canvas.drawBitmap(bmp, matrix, paint);
5、消除鋸齒
paint.setAntiAlias(true);
6、指定圓心的旋轉
matrix.setRotate(15,bmp.getWidth()/2,bmp.getHeight()/2);
Matrix matrix = new Matrix();
matrix.setRotate(15,bmp.getWidth()/2,bmp.getHeight()/2);
alteredBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(),
matrix, false);
alteredImageView.setImageBitmap(alteredBitmap);