天天看點

第52章、Bitmap圖像處理(從零開始學Android)

  在android中顯示圖像也有好多種方法,本例中使用BitmapFactory.decodeResource獲得資源圖像檔案,然後用Canvas畫布顯示位圖。由于通過自定義View代替布局檔案,故而不需要使用布局檔案。

  

一、程式檔案

  1、建立BitmapView.java檔案。

  在“src/com.genwoxue.bitmap”位置,建立BitmapView.java檔案。

  

第52章、Bitmap圖像處理(從零開始學Android)

  BitmapView.java檔案源代碼如下:

package com.genwoxue.bitmap;

import android.content.Context;  
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;
import android.view.View;


public class BitmapView extends View{
	
	Paint paint=null;
	Resources src=null;
	Bitmap bmp=null;
	
	public BitmapView(Context context) {   
		super(context);   
		
		/*----------------------------------------------
		 * 建議盡量把初始化畫筆、資源、位圖不放在onDraw方法中,這是因為:
		 * onDraw經常會運作 到的,不要在裡面new對象,越少越好,不然很浪費記憶體
		 *--------------------------------------------*/
		
		//擷取畫筆paint,初始化畫筆
		paint=new Paint();
		//擷取資源src
		src=getResources();
		// 擷取位圖
	    bmp=BitmapFactory.decodeResource(src, R.drawable.ic_launcher);
	}  
	
	@Override
	protected void onDraw(Canvas canvas){
		
		String info=null;
		int posX=0;
		int posY=0;
		
		//設定畫布背景為灰色
		canvas.drawColor(Color.GRAY);
		//顯示位圖
		canvas.drawBitmap(bmp,220,220,paint);
		
		//設定畫筆為白色
		paint.setColor(Color.WHITE);
		//字型大小為18
		paint.setTextSize(18);
		info="圖檔高度:"+bmp.getHeight()+",圖檔寬度:"+bmp.getWidth();
		posX=135;
		posY=bmp.getWidth()+260;
		
		//在posX與posY處顯示圖檔高度與寬度資訊
		canvas.drawText(info, posX,posY, paint);
	}

}
           

 2、打開MainActivity.java主檔案

  打開“src/com.genwoxue.bitmap/MainActivity.java”檔案。

  MainActivity.java檔案源代碼如下:

package com.genwoxue.bitmap;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//執行個體化GraphicsView
		BitmapView gv = new BitmapView(this); 
		
		/* 在以前我們通過setContentView(R.layout.activity_main)顯示布局檔案
		 * 本例中使用GraphicsView對象gv代替以前布局檔案
		 */
		setContentView(gv);
	}

}
           

二、運作結果

  

第52章、Bitmap圖像處理(從零開始學Android)

附:android Bitmap用法總結

1、Drawable → Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {

Bitmap bitmap = Bitmap

.createBitmap(

drawable.getIntrinsicWidth(),

drawable.getIntrinsicHeight(),

drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

: Bitmap.Config.RGB_565);

Canvas canvas = new Canvas(bitmap);

// canvas.setBitmap(bitmap);

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),

drawable.getIntrinsicHeight());

drawable.draw(canvas);

return bitmap;

}

2、從資源中擷取Bitmap

Resources res=getResources();

Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);

3、Bitmap → byte[]

private byte[] Bitmap2Bytes(Bitmap bm){

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.PNG, 100, baos);

return baos.toByteArray();

}

4、byte[] → Bitmap

private Bitmap Bytes2Bimap(byte[] b){

if(b.length!=0){

return BitmapFactory.decodeByteArray(b, 0, b.length);

}

else {

return null;

}

}

5、儲存bitmap

static boolean saveBitmap2file(Bitmap bmp,String filename){

CompressFormat format= Bitmap.CompressFormat.JPEG;

int quality = 100;

OutputStream stream = null;

try {

stream = new FileOutputStream("/sdcard/" + filename);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return bmp.compress(format, quality, stream);

}

6、将圖檔按自己的要求縮放

// 圖檔源

Bitmap bm = BitmapFactory.decodeStream(getResources()

.openRawResource(R.drawable.dog));

// 獲得圖檔的寬高

int width = bm.getWidth();

int height = bm.getHeight();

// 設定想要的大小

int newWidth = 320;

int newHeight = 480;

// 計算縮放比例

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// 取得想要縮放的matrix參數

Matrix matrix = new Matrix();

matrix.postScale(scaleWidth, scaleHeight);

// 得到新的圖檔

Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,

true);

// 放在畫布上

canvas.drawBitmap(newbm, 0, 0, paint);

7、bitmap的用法小結

BitmapFactory.Options option = new BitmapFactory.Options();

option.inSampleSize = 2; //将圖檔設為原來寬高的1/2,防止記憶體溢出

Bitmap bm = BitmapFactory.decodeFile("",option);//檔案流

URL url = new URL("");

InputStream is = url.openStream();

Bitmap bm = BitmapFactory.decodeStream(is);

android:scaleType:

android:scaleType是控制圖檔如何resized/moved來匹對ImageView的size。ImageView.ScaleType /

android:scaleType值的意義差別:

CENTER /center 按圖檔的原來size居中顯示,當圖檔長/寬超過View的長/寬,則截取圖檔的居中部分

顯示

CENTER_CROP / centerCrop 按比例擴大圖檔的size居中顯示,使得圖檔長(寬)等于或大于View的長

(寬)

CENTER_INSIDE / centerInside 将圖檔的内容完整居中顯示,通過按比例縮小或原來的size使得圖檔

長/寬等于或小于View的長/寬

FIT_CENTER / fitCenter 把圖檔按比例擴大/縮小到View的寬度,居中顯示

FIT_END / fitEnd 把圖檔按比例擴大/縮小到View的寬度,顯示在View的下部分位置

FIT_START / fitStart 把圖檔按比例擴大/縮小到View的寬度,顯示在View的上部分位置

FIT_XY / fitXY 把圖檔 不按比例 擴大/縮小到View的大小顯示

MATRIX / matrix 用矩陣來繪制,動态縮小放大圖檔來顯示。

//放大縮小圖檔

public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){

int width = bitmap.getWidth();

int height = bitmap.getHeight();

Matrix matrix = new Matrix();

float scaleWidht = ((float)w / width);

float scaleHeight = ((float)h / height);

matrix.postScale(scaleWidht, scaleHeight);

Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,

true);

return newbmp;

}

//将Drawable轉化為Bitmap

public static Bitmap drawableToBitmap(Drawable drawable){

int width = drawable.getIntrinsicWidth();

int height = drawable.getIntrinsicHeight();

Bitmap bitmap = Bitmap.createBitmap(width, height,

drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

: Bitmap.Config.RGB_565);

Canvas canvas = new Canvas(bitmap);

drawable.setBounds(0,0,width,height);

drawable.draw(canvas);

return bitmap;

}

//獲得圓角圖檔的方法

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){

Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap

.getHeight(), Config.ARGB_8888);

Canvas canvas = new Canvas(output);

final int color = 0xff424242;

final Paint paint = new Paint();

final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

final RectF rectF = new RectF(rect);

paint.setAntiAlias(true);

canvas.drawARGB(0, 0, 0, 0);

paint.setColor(color);

canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

canvas.drawBitmap(bitmap, rect, rect, paint);

return output;

}

//獲得帶倒影的圖檔方法

public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){

final int reflectionGap = 4;

int width = bitmap.getWidth();

int height = bitmap.getHeight();

Matrix matrix = new Matrix();

matrix.preScale(1, -1);

Bitmap reflectionImage = Bitmap.createBitmap(bitmap,

0, height/2, width, height/2, matrix, false);

Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2),

Config.ARGB_8888);

Canvas canvas = new Canvas(bitmapWithReflection);

canvas.drawBitmap(bitmap, 0, 0, null);

Paint deafalutPaint = new Paint();

canvas.drawRect(0, height,width,height + reflectionGap,

deafalutPaint);

canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

Paint paint = new Paint();

LinearGradient shader = new LinearGradient(0,

bitmap.getHeight(), 0, bitmapWithReflection.getHeight()

+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);

paint.setShader(shader);

// Set the Transfer mode to be porter duff and destination in

paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

// Draw a rectangle using the paint with our linear gradient

canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()

+ reflectionGap, paint);

return bitmapWithReflection;

}

}