1. 程式人生 > >Android 實現放大鏡功能原始碼

Android 實現放大鏡功能原始碼

Android 實現放大鏡功能 需用到Bitmap、BitmapShader、Matrix、Canvas、BitmapFactory等Android的類。

如下是原始碼:

package com.lulu;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;


public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout ll = (FrameLayout) findViewById(R.id.frameLayout1); // 獲取佈局檔案中的幀佈局管理器
ll.addView(new MyView(this)); // 將自定義檢視新增到幀佈局管理器中


}


public class MyView extends View {
private Bitmap bitmap; // 源影象,也就是背景影象
private ShapeDrawable drawable;


private final int RADIUS = 57; // 放大鏡的半徑


private final int FACTOR = 2; // 放大倍數
private Matrix matrix = new Matrix();
private Bitmap bitmap_magnifier; // 放大鏡點陣圖
private int m_left = 0; // 放大鏡的左邊距
private int m_top = 0; // 放大鏡的頂邊距


public MyView(Context context) {
super(context);
Bitmap bitmap_source = BitmapFactory.decodeResource(getResources(),
R.drawable.source);//獲取要顯示的源影象
bitmap = bitmap_source;
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(
bitmap_source, bitmap_source.getWidth() * FACTOR,
bitmap_source.getHeight() * FACTOR, true), TileMode.CLAMP,
TileMode.CLAMP);//建立BitmapShader物件
// 圓形的drawable
drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setShader(shader);
drawable.setBounds(0, 0, RADIUS * 2, RADIUS * 2); // 設定圓的外切矩形
bitmap_magnifier = BitmapFactory.decodeResource(getResources(),
R.drawable.magnifier);//獲取放大鏡影象
m_left = RADIUS - bitmap_magnifier.getWidth() / 2; // 計算放大鏡的預設左邊距
m_top = RADIUS - bitmap_magnifier.getHeight() / 2; // 計算放大鏡的預設右邊距
}


@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, 0, 0, null); // 繪製背景影象
canvas.drawBitmap(bitmap_magnifier, m_left, m_top, null); // 繪製放大鏡
drawable.draw(canvas); // 繪製放大後的影象
}


@Override
public boolean onTouchEvent(MotionEvent event) {
final int x = (int) event.getX(); // 獲取當前觸控點的X軸座標
final int y = (int) event.getY(); // 獲取當前觸控點的Y軸座標
matrix.setTranslate(RADIUS - x * FACTOR, RADIUS - y * FACTOR); // 平移到繪製shader的起始位置
drawable.getPaint().getShader().setLocalMatrix(matrix);
drawable.setBounds(x - RADIUS, y - RADIUS, x + RADIUS, y + RADIUS); // 設定圓的外切矩形
m_left = x - bitmap_magnifier.getWidth() / 2; // 計算放大鏡的左邊距
m_top = y - bitmap_magnifier.getHeight() / 2; // 計算放大鏡的右邊距
invalidate(); // 重繪畫布
return true;
}
}
}