1、首先说一下两个类:
Matrix Class OverviewThe Matrix class holds a 3x3 matrix for transforming coordinates. Matrix does not have a constructor, so it must be explicitly initialized using either reset() - to construct an identity matrix, or one of the set..() functions (e.g. setTranslate, setRotate, etc.).
矩阵类拥有3 x3的坐标变换矩阵。没有一个构造函数矩阵,所以它必须显式初始化的使用或重置()-如何构建一个矩阵,或者一个场景……()的功能(例如,setRotate setTranslate等。)Matrix的操作,总共分为translate(平移),rotate(旋转),scale(缩放)和skew(倾斜)四种,每一种变换在Android的API里都提供了set,post和pre三种操作方式,除了translate,其他三种操作都可以指定中心点。set是直接设置Matrix的值,每次set一次,整个Matrix的数组都会变掉。post是后乘,当前的矩阵乘以参数给出的矩阵。可以连续多次使用post,来完成所需的整个变换。
接下来我们用到了两个方法:
平移方法:两个参数分别是要移到的x、y坐标
boolean
postTranslate(float dx, float dy)
Postconcats the matrix with the specified translation.
和旋转方法:第一个参数是旋转多少度,正数是顺时针,负数是逆时针;第二三参数是按某个点旋转的x、y坐标;
boolean
postRotate(float degrees, float px, float py)
Postconcats the matrix with the specified rotation.
PointF holds two float coordinates
PointF有两个浮点坐标我们要用到该类的一个方法:设置点的x和y坐标
final void
set(float x, float y)
Set the point's x and y coordinates
2、接下来是案例:
首先看一下效果图:
旋转拖拽后布局很简单在此不再给出!直接看java代码:
[java]
public class MovePictureActivity extends Activity implements OnClickListener { private Button button1, button2; private ImageView image; PointF startPoint = new PointF();// 有两PointF浮坐标 Matrix matrix = new Matrix(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); button1.setOnClickListener(this); button2.setOnClickListener(this); image = (ImageView) findViewById(R.id.image); image.setOnTouchListener(new ImageViewOnTouchListener());// 为image绑上触摸事件监听 } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: matrix.postRotate(90, image.getWidth() / 2, image.getHeight() / 2);// 顺时针旋转90度,并且以image.getWidth()/2、image.getHeight()/2为中心旋转; break; case R.id.button2: matrix.postRotate(-90, image.getWidth() / 2, image.getHeight() / 2);// 逆时针旋转90度 break; } image.setImageMatrix(matrix); } private class ImageViewOnTouchListener implements OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) {// 这里取出来的是event.getAction()返回的值的低八位,MotionEvent.ACTION_MASK是255, case MotionEvent.ACTION_DOWN: startPoint.set(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE:// 移动过程,该事件会不断被触发 float dx = event.getX() - startPoint.x; float dy = event.getY() - startPoint.y; matrix.postTranslate(dx, dy); startPoint.set(event.getX(), event.getY()); break; } image.setImageMatrix(matrix); return true; } } } 为image绑定监听事件,