最近寫電子書程式,設計到對映像的處理,主要是對 Bitmap 的處理,所以有一點小小的心得,拿出來跟大家分享一下。
要把一個 Bitmap 畫到 View 上,必須用到的類有 android.graphics.Canvas, 和 android.graphics.Bitmap 。方法很簡單,在 View 裡面,重載 onDraw(Canvas canvas) 方法,然後用 canvas.drawBitmap() 方法,將其畫在螢幕上。
Java代碼
- public class MyView extends View {
- private Bitmap mBitmap;
- public MyView(Context context) {
- super(context);
- initialize();
- }
- private void initialize() {
- Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();
- mBitmap = bmp;
- }
- @Override protected void onDraw(Canvas canvas) {
- // super.onDraw(canvas); //當然,如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。
- canvas.drawBitmap(mBitmap, 0, 0, null);
- }
- }
public class MyView extends View {private Bitmap mBitmap;public MyView(Context context) {super(context);initialize();}private void initialize() {Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();mBitmap = bmp;}@Override protected void onDraw(Canvas canvas) {//super.onDraw(canvas); //當然,如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。canvas.drawBitmap(mBitmap, 0, 0, null);}}
結果:
原圖:
雖然這僅僅只是第一步,但是很鼓舞人心呢,呵呵。
上面是直接將原圖畫在螢幕上,沒有任何處理,因為圖片比螢幕大,所以超出的部分看不到。我們試著將圖片展開以填滿整個螢幕。
Java代碼
- public class MyView extends View {
- private Bitmap mBitmap;
- private Matrix mMatrix = new Matrix();
- private static int mScreenWidth;
- private static int mScreenHeight;
- public MyView(Context context) {
- super(context);
- initialize();
- }
- private void initialize() {
- DisplayMetrics dm = getResources().getDisplayMetrics();
- mScreenWidth = dm.widthPixels;
- mScreenHeight = dm.heightPixels;
- Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();
- mBitmap = Bitmap.createScaledBitmap(bmp, mScreenWidth, mScreenHeight, true);
- }
- @Override protected void onDraw(Canvas canvas) {
- // super.onDraw(canvas); //當然,如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。
- canvas.drawBitmap(mBitmap, 0, 0, null);
- }
- }
public class MyView extends View {private Bitmap mBitmap;private Matrix mMatrix = new Matrix();private static int mScreenWidth;private static int mScreenHeight;public MyView(Context context) {super(context);initialize();}private void initialize() {DisplayMetrics dm = getResources().getDisplayMetrics();mScreenWidth = dm.widthPixels;mScreenHeight = dm.heightPixels;Bitmap bmp = ((BitmapDrawable)getResources().getDrawable(R.drawable.show)).getBitmap();mBitmap = Bitmap.createScaledBitmap(bmp, mScreenWidth, mScreenHeight, true);}@Override protected void onDraw(Canvas canvas) {//super.onDraw(canvas); //當然,如果介面上還有其他元素需要繪製,只需要將這句話寫上就行了。canvas.drawBitmap(mBitmap, 0, 0, null);}}
顯示結果:
下面一篇將介紹對Bitmap的一些操作。