簡體   English   中英

獲取觸摸事件相對於圖像的坐標

[英]Get coordinates of touch event relative to Image

我有一個以屏幕為中心的圖像。 我需要使其可觸摸,並且需要獲取觸摸事件相對於圖像的坐標。 我已將我的圖像包裝在 TouchableOpacity 中以使其可觸摸。 問題是觸摸坐標是相對於 TouchableOpacity 而不是圖像。 TouchableOpacity 占據了整個屏幕,但圖像在其中居中。

我要么需要使我的 TouchableOpacity 與圖像的大小相同,要么我需要知道 TouchableOpacity 中圖像的偏移量。

我曾嘗試使用 OnLayout 和 NativeEvent 對象來獲取圖像在其父級中的位置,但它只返回 0,0。

    const {width, height} = Dimensions.get("window");

    class Inspection extends React.Component {

        handlePress(evt) {
            // do stuff
            ...
        }

        render() {
            return (
                <View style={{flex:1, backgroundColor:'#fff'}}>
                    <TouchableOpacity 
                        onPress={(evt) => this.handlePress(evt)}
                        style={{backgroundColor: '#3897f0'}}
                    >
                        <Image 
                            onLayout={({nativeEvent}) => {
                                console.log(nativeEvent.layout);
                            }}
                            source={require('../../images/wireframe-car.jpg')}
                            resizeMode='contain'
                            style={{
                                maxHeight: height,
                                maxWidth: width
                                }} 
                        />
                    </TouchableOpacity>
                </View>
            );
        }
    }

控制台輸出:

{height: 683.4285888671875, width: 411.4285583496094, y: 0, x: 0}

我已經為 TouchableOpacity 添加了一個 backgroundColor,所以你可以看到它占據了整個屏幕。

截屏

還有另一種方法嗎?

TouchableOpacity將與Image 的大小相同,因為您沒有給它任何高度,您只需要像這樣將onLayout 屬性分配給您的TouchableOpacity

      <View
        style={{ flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' }}>
        <TouchableOpacity
          onLayout={({ nativeEvent }) => {
            console.log(nativeEvent.layout)
          }}
          style={{}}
          onPress={evt => this.handlePress(evt)}>
          <Image
            source={require('../../images/wireframe-car.jpg')}
            resizeMode="contain"
            style={{
              maxWidth: '100%',
            }}
          />
        </TouchableOpacity>
      </View>

這將為您提供圖像的確切 x 和 y。

更新

問題也出在圖像尺寸上,因為圖像尺寸很大,所以它占用了設備的高度,我們得到了 x:0 和 y:0,為了解決這個問題,我們可以給 Image 組件一個靜態高度或根據寬度計算其高度。 我們可以像這樣從本地路徑獲取寬度和高度圖像:

let imageUri = Image.resolveAssetSource(require('../../images/wireframe-car.jpg').uri)
    Image.getSize(imageUri , (width, height) => { 
    console.log(`The image dimensions are ${width}x${height}`); 
    }, (error) => { 
    console.error(`Couldn't get the image size: ${error.message}`); 
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM