首頁 > Java > 主體

偵測 imageView 中特定 x 和 y 座標的點擊

WBOY
發布: 2024-02-14 08:06:09
轉載
987 人瀏覽過

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.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!