我想在屏幕上随机移动我的痣图像,但是我不确定该怎么做,有人可以帮我吗?我找到了一些有关如何从左向右移动它的信息,但这并不是我想要的,谢谢。
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:background="@drawable/ground"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/moleImage"
android:layout_width="65dp"
android:layout_height="65dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@drawable/mole" />
</androidx.constraintlayout.widget.ConstraintLayout>
答案 0 :(得分:1)
看看这是否适合您
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_image);
iv = findViewById(R.id.moleimage);
positionImage();
}
public void positionImage() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
int DeviceTotalWidth = metrics.widthPixels;
int DeviceTotalHeight = metrics.heightPixels;
float randX = getRandomPositionX(DeviceTotalWidth);
float randY = getRandomPositionY(DeviceTotalHeight);
Log.d(TAG, "positionImage: totalX: " + DeviceTotalWidth + " totalY: " + DeviceTotalHeight);
Log.d(TAG, "positionImage: ranX: " + randX + " ranY: " + randY);
iv.setX(randX);
iv.setY(randY);
}
public float getRandomPositionX(float deviceTotalWidth) {
Random random = new Random();
float randX = random.nextInt((int) deviceTotalWidth - (int) getImageSizeinPixels());
return randX;
}
public float getRandomPositionY(float DeviceTotalHeight) {
Random random = new Random();
float randY = random.nextInt((int) DeviceTotalHeight - (int) getImageSizeinPixels());
return randY;
}
public float getImageSizeinPixels() {
// Converts 65 dip into its equivalent px
float imageSize = 65f;
float extraPadding = 40f;
float dip = imageSize + extraPadding;
Resources r = getResources();
float px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dip,
r.getDisplayMetrics()
);
return px;
}
答案 1 :(得分:0)
您需要主Layout
,其中imageview
作为子布局。
将onTouchListerner
添加到主布局。主布局可以是relativelayout
,linearlayout
等之类的任何布局。
mainlayout.setOnTouchListener(this);
现在实现onTouch
方法
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = (float) event.getX();
float y = (float) event.getY();
yourImageView.setX(x);
yourImageView.setY(y);
return true;
}
我希望这对您有用。