Changing CGrect value to user coordinate system

风格不统一 提交于 2019-12-04 11:51:24

问题


I have a CGRect; can I transfer its coordinates to be in the user coordinate system, i.e., bottom left corner to top instead of top left corner to bottom. Is there any predefined method for this or do I need to calculate it manually? Thanks in Advance.


回答1:


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



来源:https://stackoverflow.com/questions/5482539/changing-cgrect-value-to-user-coordinate-system

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