erica / iphone-3.0-cookbook-

Sample Code
912 stars 305 forks source link

CGRectMoveToCenter #20

Closed lupugabriel closed 11 years ago

lupugabriel commented 11 years ago

I bought your book: IOS cookbook and I have a short question, if u have time to answer: The method below that is included in "UIView-ViewFrameGeometry.h" has an error.

// if i make a Rect CGRect myRect = CGRectMake(10, 10, 10, 10);

NSLog(@"%@",NSStringFromCGRect(myRect));

// and try to move to Center (100,100)

myRect = CGRectMoveToCenter(myRect, CGPointMake(100, 100));

NSLog(@"%@",NSStringFromCGRect(myRect));

2013-03-15 11:56:05.014 HelloWorld[789:11303] {{10, 10}, {10, 10}}

2013-03-15 11:56:09.240 HelloWorld[789:11303] {{85, 85}, {10, 10}}

CGRect CGRectMoveToCenter(CGRect rect, CGPoint center) { CGRect newrect = CGRectZero; newrect.origin.x = center.x-CGRectGetMidX(rect); newrect.origin.y = center.y-CGRectGetMidY(rect); newrect.size = rect.size; return newrect; }

So, i guess its a mistake or maybe I didnt understand the purpose of this method! I thought that this method should move a rect to another coordonates and his new center will be the CGpoint I wanted. So the method should look like this:

CGRect CGRectMoveToCenter(CGRect rect, CGPoint center) { CGRect newrect = CGRectZero; newrect.origin.x = center.x-(CGRectGetMidX(rect)-rect.origin.x); newrect.origin.y = center.y-(CGRectGetMidY(rect)-rect.origin.y); newrect.size = rect.size; return newrect; }

erica commented 11 years ago

Even better, let me give you an entirely new function:

CGRect RectAroundCenter(CGPoint center, CGSize size) { CGFloat halfWidth = size.width / 2.0f; CGFloat halfHeight = size.height / 2.0f;

return CGRectMake(center.x - halfWidth, center.y - halfHeight, size.width, size.height);

}

e.g. CGRect myRect = CGRectMake(10, 10, 10, 10); CGRect result = RectAroundCenter(CGPointMake(100, 100), myRect.size);

Cheers! -- E