Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing CGrect value to user coordinate system

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.

like image 399
ajay Avatar asked Mar 30 '11 06:03

ajay


1 Answers

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 Hopefully this image makes it clearer

like image 130
Roberto Avatar answered Sep 28 '22 09:09

Roberto