Changing CGrect value to user coordinate system

情到浓时终转凉″ 提交于 2019-12-03 08:16:12

To convert a rectangle from a coordinate system that has its origin at the bottom left (let's just call it traditional coordinate system to give it name) to a system where the origin is at the top left (iPhone coordinate system) you need to know the size of the view where the CGRect is, since the view is the reference for the rectangle.

For example, let's say you have a view with size 200 x 300, and the CGRect you have is CGRectMake(10, 20, 30, 40). The size of the CGRect will remain the same. All that will change is the origin - actually, only the y coordinate will change and not the x coordinate, because the traditional and iPhone coordinate systems both start on the left side (one at the bottom left; the other at the top left).

So we will have something like CGRectMake(10, y, 30, 40).

  - (CGRect)rectangle:(CGRect)oldRect fromTraditionalToiPhoneCoordinatesWithReferenceViewOfSize:(CGSize)aSize
     {
      CGFloat oldY = oldRect.origin.y;  // This is the old y measured from the bottom left. 
      CGFloat newY = aSize.height - oldY - oldRect.size.height;

      CGRect newRect = oldRect;
      newRect.origin.y = newY;

      return newRect;
     }

The new rectangle, as measured from an iPhone (top left) coordinate system, would be: CGRectMake(10, 300 - 20 - 40, 30, 40) = CGRectMake(10, 240, 30, 40).

Hopefully this image makes it clearer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!