Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 放大鏡

Android 放大鏡

編輯:關於Android編程

之前做過iOS下的放大鏡功能,這個再來一個Android版的。下載地址:http://download.csdn.net/detail/qqmcy/7038411

ShaderView.java

package com.pactera.magnifierdemo;

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.view.MotionEvent;
import android.view.View;

/**
 * 放大鏡實現方式1
 * 
 * @author 杜甲同學
 * 
 */

public class ShaderView extends View {
	private final Bitmap bitmap;
	private final ShapeDrawable drawable;
	// 放大鏡的半徑

	private static final int RADIUS = 50;
	// 放大倍數

	private static final int FACTOR = 3;
	private final Matrix matrix = new Matrix();

	public ShaderView(Context context) {
		super(context);
		Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.changmen);
		bitmap = bmp;
		BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(bmp,
				bmp.getWidth() * FACTOR, bmp.getHeight() * FACTOR, true),
				TileMode.CLAMP, TileMode.CLAMP);
		// 圓形的drawable

		drawable = new ShapeDrawable(new OvalShape());
		drawable.getPaint().setShader(shader);
		drawable.setBounds(0, 0, RADIUS * 2, RADIUS * 2);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		final int x = (int) event.getX();
		final int y = (int) event.getY();
		// 這個位置表示的是,畫shader的起始位置

		matrix.setTranslate(RADIUS - x * FACTOR, RADIUS - y * FACTOR);
		drawable.getPaint().getShader().setLocalMatrix(matrix);
		// bounds,就是那個圓的外切矩形

		drawable.setBounds(x - RADIUS, y - RADIUS, x + RADIUS, y + RADIUS);
		invalidate();
		return true;
	}

	@Override
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawBitmap(bitmap, 0, 0, null);
		drawable.draw(canvas);
	}
}


MainActivity.java

package com.pactera.magnifierdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		ShaderView view = new ShaderView(getBaseContext());
		addContentView(view, params);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved