Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 在螢幕任意點移動圖片:onTouchEvent 與邊界處理(附源碼)

onTouchEvent(MotionEvent event)這個方法用過很多次,卻沒想過能拿來做拖曳。試寫之後發現效果意外地順手,做小遊戲時應該很用得上:手指在螢幕上滑,圖片就緊跟著跑。以下把實作與踩過的坑一起分享。

程式啟動時圖片置中;點擊螢幕左上角,圖片移動過去。

點擊左下角。

點擊右下角。

核心觀念

整個效果靠兩件事支撐:一是用 DisplayMetrics 取得螢幕解析度,二是覆寫 onTouchEvent 攔下 ACTION_DOWN、ACTION_MOVE、ACTION_UP 三種事件,每次都呼叫同一個 picMove 方法更新位置。位置更新則是重新設定 AbsoluteLayout.LayoutParams,把新的 x、y 交給 setLayoutParams。

最容易忽略的是邊界。若只把圖片左上角對齊手指,拖到四邊時圖片會有一半跑出螢幕,甚至完全消失再也拉不回來。程式中針對上下左右各做了一次夾限,並在計算時扣掉圖片寬高的一半,讓圖片中心而非左上角貼合手指。

MainActivity.java

在 TouchDemo 專案的 com.cn.daming 套件下:

package com.cn.daming;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ImageView mImageView01;
    private int intWidth, intHeight, intDefaultX, intDefaultY;
    private float mX, mY;
    private int intScreenX, intScreenY;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        drawBackground();

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        intScreenX = dm.widthPixels;
        intScreenY = dm.heightPixels;

        intWidth = 100;
        intHeight = 100;

        mImageView01 = (ImageView) findViewById(R.id.myImageView1);
        mImageView01.setImageResource(R.drawable.body);

        RestoreButton();

        mImageView01.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                RestoreButton();
            }
        });
    }

    // 漸層背景
    public void drawBackground() {
        GradientDrawable grad = new GradientDrawable(
                Orientation.TL_BR,
                new int[] {
                    Color.rgb(0, 0, 127),
                    Color.rgb(0, 0, 255),
                    Color.rgb(127, 0, 255),
                    Color.rgb(127, 127, 255),
                    Color.rgb(127, 255, 255),
                    Color.rgb(255, 255, 255)
                });
        this.getWindow().setBackgroundDrawable(grad);
    }

    /* 覆蓋觸控事件 */
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        try {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                picMove(x, y);
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /* 移動圖片 */
    private void picMove(float x, float y) {
        mX = x - (intWidth / 2);
        mY = y - (intHeight / 2);

        if ((mX + intWidth) > intScreenX) {
            mX = intScreenX - intWidth;
        } else if (mX < 0) {
            mX = 0;
        } else if ((mY + intHeight) > intScreenY) {
            mY = intScreenY - intHeight;
        } else if (mY < 0) {
            mY = 0;
        }

        Log.i("jay", Float.toString(mX) + "," + Float.toString(mY));

        mImageView01.setLayoutParams(
                new AbsoluteLayout.LayoutParams(intWidth, intHeight, (int) mX, (int) mY));
    }

    /* 還原圖片位置 */
    public void RestoreButton() {
        intDefaultX = ((intScreenX - intWidth) / 2);
        intDefaultY = ((intScreenY - intHeight) / 2);

        mMakeTextToast("(" + Integer.toString(intDefaultX) + ","
                + Integer.toString(intDefaultY) + ")", true);

        mImageView01.setLayoutParams(
                new AbsoluteLayout.LayoutParams(intWidth, intHeight, intDefaultX, intDefaultY));
    }

    /* 自訂提示訊息 */
    public void mMakeTextToast(String str, boolean isLong) {
        if (isLong == true) {
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:id="@+id/widget27"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_x="80dip"
        android:text="@string/hello" />

    <ImageView
        android:id="@+id/myImageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ImageView>

</AbsoluteLayout>

實務上若目標 API 較新,可改用 FrameLayout 搭配 translationX/translationY 來移動,比重新配置 LayoutParams 更省資源;AbsoluteLayout 亦已被標示為不建議使用。

Copyright © Linux教程網 All Rights Reserved