點選這裡可以檢視我所有關于圖形圖像處理的文章
簡單圖檔包括Bitmap和BitmapFactory兩類。
Bitmap用于顯示一張位圖,BitmapFactory用于封裝一個Bitmap對象。
如果想将Bitmap封裝成一個BitmapFactory對象,可以調用BitmapDrawable的構造方法。
Bitmap bitmap = BitmapFactory.decodeFile("draw1.jpg");
BitmapDrawable bd = new BitmapDrawable(bitmap);
如果需要擷取BitmapDrawable包裝的 Bitmap對象,可以調用 BitmapDrawable的getBitmap()方法。
Bitmap類常用函數
編号 | 方 法 | 描 述 |
---|---|---|
1 | createBitmap(Bitmap source,int x,int y,int width,int height) | 從原位圖source的指定坐标點(x,y)開始,截取寬為width,長為height的部分,建立一個新的Bitm對象 |
2 | createBitmap(int width,int height,Bitmap.Config cpnfig) | 建立一個寬度為width,長為height的新位圖 |
3 | getHeight() | 擷取位圖的高度 |
4 | getWidth() | 擷取位圖的寬度 |
5 | isRecycle() | 傳回該Bitmap對象是否已被收回 |
6 | recycle() | 強制一個Bitmap對象立刻收回自己 |
簡單圖檔執行個體—圖檔放大器
說明:這個圖檔放大器要實作的功能就:是在一張圖檔上我們點選哪個區域,會對該處的細節進行放大處理。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/bitmap1"
android:layout_width="match_parent"
android:layout_height="240dp"
android:scaleType="fitXY"/>
<ImageView
android:id="@+id/bitmap2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"/>
</LinearLayout>
MainActivity.java
package com.file.file;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView bitmap1 = (ImageView)findViewById(R.id.bitmap1);
final ImageView bitmap2 = (ImageView)findViewById(R.id.bitmap2);
// 擷取圖檔
bitmap1.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.cat));
bitmap1.setOnTouchListener(new View.OnTouchListener() {
@Override
// 設定觸摸監聽器
public boolean onTouch(View view, MotionEvent motionEvent) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)bitmap1.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
float xchange = bitmap.getWidth()/(float)bitmap1.getWidth();
float ychange = bitmap.getHeight()/(float)bitmap1.getHeight();
int x = (int)(motionEvent.getX() * xchange);
int y = (int)(motionEvent.getY() * ychange);
// 擷取原圖和手機上照片顯示的比例(一般手機會對圖檔按比例縮小)
// 我在下面設定的是以(x,y)為中心,長寬各為100的正方形
// 如果X/Y +50 > 圖檔的長度/寬度,就表名這已經到達邊緣
// 那麼就将中心設定在距離邊緣50位置,以下雷同
if (x+>bitmap.getWidth()){
x = bitmap.getWidth()-;
}
if (x-<){
x=;
}
if (y+>bitmap.getHeight()){
y = bitmap.getHeight()-;
}
if (y-<){
y=;
}
bitmap2.setImageBitmap(Bitmap.createBitmap(bitmap,x-,y-,,));
bitmap2.setVisibility(View.VISIBLE);
return false;
}
});
}
}
實作效果截圖
