簡體   English   中英

如何根據用戶對圖像的觸摸獲得X和Y坐標,在任何設備上都相同

[英]How can I get an X and Y coordinate, based on a user's touch on an image, that will be the same on any device

例如,我在整個屏幕上顯示一個笑臉,並按比例調整以適合寬高比。 用戶觸摸笑臉的左眼。 無論用戶使用什么設備,如何保證返回的X和Y坐標都相同?

考慮到設備的縱橫比以及圖像縮放比例,我一直在嘗試解決這一問題。 似乎無論我做什么,結果總是至少在某些設備上有所不同。

我目前正在嘗試針對iOS解決這一問題,但最終還是要針對Android執行相同的操作。 有什么建議么? 包括可以提供幫助的pod /庫就可以了。

所以,我遇到麻煩主要是因為我在情節提要中的限制。 對於下面的代碼,您需要確保高度和寬度與(縮放的)圖像匹配,而不與視圖或屏幕尺寸匹配-因此,僅選擇“寬高比”內容模式並放大圖像是行不通的。 我添加了一個寬高比約束,以及一些靈活的尾部和前導空格(> = 0)。 無論如何,如果可以使圖像的“邊界”成功地圍繞圖像的實際邊界,則應該設置為使用以下代碼。

該代碼基於圖像獲取觸摸的坐標,然后根據寬高比計算該觸摸的X / Y值在哪里。 因此,即使您的手機上有幾千個像素,在200x300笑臉中位於100x150的左眼觸摸也會成功返回“ X:100 Y:150”。

@IBOutlet weak var image: UIImageView!

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    if let touch = touches.first {
        //based on the touch on an image, grab the X/Y value
        let imageViewPoint = touch.location(in: self.image)

        //get the ratio by dividing the scaled bounds of the image by the unscaled size of the image
        let widthRatio = image.bounds.size.width / (image.image?.size.width)!
        let heightRatio = image.bounds.size.height / (image.image?.size.height)!

        //divide the touch coordinates by the ratios to get your result
        let endResultX = imageViewPoint.x / widthRatio
        let endResultY = imageViewPoint.y / heightRatio

        print("X End Result: ", endResultX)
        print("Y End Result: ", endResultY)
    }
}

暫無
暫無

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

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