OStack程序员社区-中国程序员成长平台

标题: iOS 触控坐标系 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:53
标题: iOS 触控坐标系

This method returns the current location of a UITouch object in the coordinate system of the specified view. Because the touch object might have been forwarded to a view from another view, this method performs any necessary conversion of the touch location to the coordinate system of the specified view.

    - (void)sendEventUIEvent *)event
    {
        if([event type] == UIEventTypeTouches)
        {
            NSSet<UITouch *> *allTouches = [event allTouches];
            if(allTouches)
            {
                for(UITouch* touch in allTouches)
                {
                    if([touch type] == UITouchTypeDirect)
                    {
                         // This is 640x1136
                         CGRect bounds = [myWindow bounds];

                         // This is in [318x560] empirically 
                         CGPoint origin = [touch locationInView:myWindow];
                    }
                }    
            }    
        }
    }

谁能解释一下?

来自问题:

  1. 在物理 iPhone 6 设备上进行测试。
  2. myWindow 是应用程序的主窗口。在 application: application didFinishLaunchingWithOptions: launchOptions
  3. 期间使用 myWindow = [[myWindow alloc] initWithFrame:[[UIScreen mainScreen] nativeBounds]]; 创建
  4. myWindow 没有 subview 。只有一个CAEAGLLayer



Best Answer-推荐答案


每个 View 都有一个 contentScaleFactor 属性。它旨在简化使用不同设备分辨率的工作(例如视网膜 (@2x)、非视网膜 (@1x)、@3x 等) UIWindowUIView 的子类,所以它也有它。

The scale factor determines how content in the view is mapped from the logical coordinate space (measured in points) to the device coordinate space (measured in pixels). This value is typically either 1.0 or 2.0. Higher scale factors indicate that each point in the view is represented by more than one pixel in the underlying layer. For example, if the scale factor is 2.0 and the view frame size is 50 x 50 points, the size of the bitmap used to present that content is 100 x 100 pixels.

The default value for this property is the scale factor associated with the screen currently displaying the view. If your custom view implements a custom drawRect: method and is associated with a window, or if you use the GLKView class to draw OpenGL ES content, your view draws at the full resolution of the screen. For system views, the value of this property may be 1.0 even on high resolution screens.

因此,在您的情况下,[myWindow bounds] 返回等于设备屏幕大小的逻辑大小,因为您将其设置为 native 边界。您的窗口在设备坐标中比屏幕大两倍,设备坐标是根据其比例因子(等于 2)根据其逻辑坐标计算得出的,并且您的触摸仅命中它的第四部分。

myWindow = [[myWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
myWindow.layer.contentsScale = [[UIScreen mainScreen] nativeScale];

CGPoint origin = [touch locationInView:myWindow];
origin.x *= [[UIScreen mainScreen] scale];
origin.y *= [[UIScreen mainScreen] scale];               

关于iOS 触控坐标系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35591681/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4