Android缩放图片
主布局文件如下:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
业务代码如下:
MainActivity.java
public class MainActivity extends Activity {
private RelativeLayout relativeLayout;
private ImageView iv;
private float currentDistance;
private float lastDistance = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
relativeLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//System.out.println("action down");
break;
case MotionEvent.ACTION_UP:
//System.out.println("action up");
break;
case MotionEvent.ACTION_MOVE:
if(event.getPointerCount() == 2) {
float offsetX = event.getX(0) - event.getX(1);
float offsetY = event.getY(0) - event.getY(1);
currentDistance = (float) Math.sqrt(offsetX*offsetX +offsetY*offsetY);
if(lastDistance < 0) {
lastDistance = currentDistance;
} else {
if(currentDistance - lastDistance > 15) {
System.out.println("放大");
RelativeLayout.LayoutParams params = (LayoutParams) iv.getLayoutParams();
params.width = (int) (1.1 * iv.getWidth());
params.height = (int) (1.1 * iv.getHeight());
iv.setLayoutParams(params);
lastDistance = currentDistance;
} else if(lastDistance - currentDistance > 15) {
System.out.println("缩小");
RelativeLayout.LayoutParams params = (LayoutParams) iv.getLayoutParams();
params.width = (int) (0.9 * iv.getWidth());;
params.height = (int) (0.9 * iv.getHeight());
iv.setLayoutParams(params);
lastDistance = currentDistance;
}
}
}
break;
}
return true;
}
});
}
}