Android:ImageView图片缩放、居中
几个重要知识点:
1、布局文件中android:scaleType="matrix" 设置图片动态缩放
2、matrix.postTranslate(dx,dy); 平移图片 matrix.postScale(sx,sy,p.x,p.y); 缩放图片
3、两点的中点、距离计算方式,限制缩放范围函数,在指定区域内移动图片方法
(以下代码网上很多地方有类似的,仅供参考)
[java]
public class Main extends Activity
{
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private float oldDist;
private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private PointF start = new PointF();
private PointF mid = new PointF();
ImageView view;
Bitmap bitmap;
DisplayMetrics dm;
float minScaleR=0.1f; //最少缩放比例
static final float MAX_SCALE = 4f; //最大缩放比例
float dist = 1f;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (ImageView) findViewById(R.id.image_view);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm); //获取分辨率
matrix.setScale(minScaleR, minScaleR); //开始先缩小
matrix.postTranslate(120, 120); //图片的位置相对于imageview的左上角往右往下各偏移120个像素
view.setImageMatrix(matrix);
view.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
ImageView view = (ImageView) v;
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN: //单点
Toast.makeText(Main.this, bitmap.getWidth()+"*"+bitmap.getHeight(), Toast.LENGTH_LONG).show();
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_UP: //单点弹起
case MotionEvent.ACTION_POINTER_UP: //多点弹起
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: //多点
oldDist = spacing(event);
if (oldDist > 10f)
{
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_MOVE: //按下且在拖动
if (mode == DRAG)
{
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x,event.getY() - start.y); //xy方向都可以拖动
//matrix.postTranslate(event.getX() - start.x,0); //只在x轴方向拖动 即左右拖动 上下不动
//matrix.postTranslate(0,event.getY() - start.y); //只在y轴方向拖动 即上下拖动 左右不动
&n
补充:移动开发 , Android ,