android 圖片縮放

圖片縮放

package com.eoeandroid.demo.testcode;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;

public class bitmaptest extends Activity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTitle("eoeAndroid教程: 縮放和旋轉圖片 -by:IceskYsl");
LinearLayout linLayout = new LinearLayout(this);

// 加載需要操作的圖片,這裏是eoeAndroid的logo圖片
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.eoe_android);

//獲取這個圖片的寬和高
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();

//定義預轉換成的圖片的寬度和高度
int newWidth = 200;
int newHeight = 200;

//計算縮放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// 創建操作圖片用的matrix對象
Matrix matrix = new Matrix();

// 縮放圖片動作
matrix.postScale(scaleWidth, scaleHeight);

//旋轉圖片 動作
matrix.postRotate(45);

// 創建新的圖片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);

//將上面創建的Bitmap轉換成Drawable對象,使得其可以使用在ImageView, ImageButton中
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

//創建一個ImageView
ImageView imageView = new ImageView(this);

// 設置ImageView的圖片爲上面轉換的圖片
imageView.setImageDrawable(bmd);

//將圖片居中顯示
imageView.setScaleType(ScaleType.CENTER);

//將ImageView添加到佈局模板中
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);

// 設置爲本activity的模板
setContentView(linLayout);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章