基于Empty Activity模板创建安卓应用后导入图片和背景/
打开String更改标题
约束布局改为线性布局并增加图像控件
然后在MainActivity里编辑剩余代码。
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout root;
private ImageView ivMickey;
private float x1, y1;
private float x2, y2;
private float nextX1, nextY1;
private float nextX2, nextY2;
private float distance;
private float nextDistance;
private LinearLayout.LayoutParams layoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = findViewById(R.id.root);
ivMickey = findViewById(R.id.iv_mickey);
root.setFocusable(true);
root.requestFocus();
layoutParams = (LinearLayout.LayoutParams) ivMickey.getLayoutParams();
root.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getPointerCount() == 1) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
layoutParams.leftMargin = (int) (event.getX() - ivMickey.getWidth() / 2);
layoutParams.topMargin = (int) (event.getY() - ivMickey.getHeight() / 2);
}
} else if (event.getPointerCount() == 2) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getX(0);
y1 = event.getY(0);
x2 = event.getX(1);
y2 = event.getY(1);
distance = (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
break;
case MotionEvent.ACTION_MOVE:
nextX1 = event.getX(0);
nextY1 = event.getY(0);
nextX2 = event.getX(1);
nextY2 = event.getY(1);
nextDistance = (float) Math.sqrt((nextX1 - nextX2) * (nextX1 - nextX2) + (nextY1 - nextY2) * (nextY1 - nextY2));
break;
case MotionEvent.ACTION_UP:
break;
}
if (nextDistance > distance) {
if (layoutParams.width < 1200) {
layoutParams.width = (int) (layoutParams.width * 1.05);
layoutParams.height = (int) (layoutParams.height * 1.05);
}
} else {
if (layoutParams.width > 10) {
layoutParams.width = (int) (layoutParams.width / 1.05);
layoutParams.height = (int) (layoutParams.height / 1.05);
}
}
x1 = nextX1;
y1 = nextY1;
x2 = nextX2;
y2 = nextY2;
distance = (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
ivMickey.setLayoutParams(layoutParams);
return true;
}
});
}
}