CGRect normalization between 0 and 1

What is the best way to normalize CGRect values CGRect that they are between 0 and 1 (single coordinate system)?

+7
source share
3 answers

A very concise way to do this:

 CGAffineTransform t = CGAffineTransformMakeScale(1.0 / parentRect.size.width, 1.0 / parentRect.size.height); CGRect unitRect = CGRectApplyAffineTransform(rect, t); 
+14
source

That should do the trick. You just need to divide everything by the width / height of the parent view or layer.

 CGFloat parentWidth = parentView.bounds.size.width; CGFloat parentHeight = parentView.bounds.size.height; CGRect rectToConvert = ...; rectToConvert.origin.x /= parentWidth; rectToConvert.origin.y /= parentHeight; rectToConvert.size.width /= parentWidth; rectToConvert.size.height /= parentHeight; 

We say that these kinds of rectangles and points are in the β€œunit coordinate system”. You can read more about this in the Core Animation Programming Guide .

+9
source

How about this:

 CGRect rectToConvert; NSAffineTransform *n = [NSAffineTransform transform]; [n scaleXBy:rectToConvert.size.width yBy:rectToConvert.size.height]; [n invert]; CGRect normalizedRect; normalizedRect.origin = [n transformPoint:rectToConvert.origin]; normalizedRect.size = [n transformSize: rectToConvert.size]; CGPoint anyPointINeedToConvert; CGPoint convertedPoint = [n transformPoint:anyPointINeedToConvert]; 

I think this makes things a little easier and allows you to take care of translations in an obvious way if you need to do them.

0
source

All Articles