搜尋
首頁Java偵測 imageView 中特定 x 和 y 座標的點擊

php小編西瓜今天要為大家介紹的是如何在 imageView 中偵測特定 x 和 y 座標的點擊。在開發行動應用程式時,我們經常需要對使用者的觸控事件進行處理,尤其是對於圖片展示的控制項(如 imageView)中的點擊事件,需要準確地獲取使用者點擊的位置資訊。本文將向大家詳細解釋如何使用 Android Studio 中的相關方法來實現這項功能,幫助開發者們更好地處理使用者的點擊操作。讓我們一起來看看吧!

問題內容

我的桌面上有一張圖像,我已使用「畫圖」應用程式開啟該圖像,並取得了包含x 和y 像素的特定位置,例如:374,207 px 但是當我將圖像添加到我的 android 應用程式並使用例如觸控座標時,它們不一樣嗎?當我點擊 imageview 中的相同位置時,我得到不同的值,結果位置的數字比我的 pc 中的數字高得多。

我已經研究這個問題大約三天了,現在我需要你的幫助。

我在網路上嘗試了不同的解決方案,例如嘗試反轉觸控位置以取得像素值,如下例所示: http://android-er.blogspot.com/2012/10/get-touched-pixel-color-of-scaled.html?m=1

但是我得到的 x 和 y 座標又不一樣 x:592 y:496

這是我的 android 應用程式程式碼:

View.OnTouchListener imgSourceOnTouchListener
            = new View.OnTouchListener(){
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float eventX = event.getX();
            float eventY = event.getY();
            float[] eventXY = new float[] {eventX, eventY};

            Matrix invertMatrix = new Matrix();
            ((ImageView)view).getImageMatrix().invert(invertMatrix);

            invertMatrix.mapPoints(eventXY);
            int x = Integer.valueOf((int)eventXY[0]);
            int y = Integer.valueOf((int)eventXY[1]);


            Drawable imgDrawable = ((ImageView)view).getDrawable();
            Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();


            //Limit x, y range within bitmap
            if(x < 0){
                x = 0;
            }else if(x > bitmap.getWidth()-1){
                x = bitmap.getWidth()-1;
            }

            if(y < 0){
                y = 0;
            }else if(y > bitmap.getHeight()-1){
                y = bitmap.getHeight()-1;
            }
            
            Log.d(TAG,"X:"+x+" Y:"+y);
            return true;
        }};

編輯:似乎它與放大圖像有關,但現在的問題是如何將縮放後的圖像與資料庫中的 x 和 y 值映射?

解決方法

將評論移至答案。

假設您知道原始尺寸(來自資料庫?)並且可以在視圖上使用 wrap_content 然後使用(以寬度為例):

public boolean onTouch(View v, MotionEvent event) {

    // get actual width of view on screen (pixels)
    int w = v.getWidth(); 

    // x coordinate in view's coordinate space
    float tw = event.getX(); 

    // ratio between x coordinate and view width
    float ratioVw = (tw / w); 

    // apply same ratio to original image width.
    int origTouchX = (int) (ratioVw * (origW)); //(origW is original width).

    return true;
}

重複高度 (y)。

以上是偵測 imageView 中特定 x 和 y 座標的點擊的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!