Normalising CGRect between 0 and 1

前端 未结 3 463
遥遥无期
遥遥无期 2021-01-04 19:18

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

相关标签:
3条回答
  • 2021-01-04 19:27

    This 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 these kinds of rects and points are in the "unit coordinate system". You can read more about it in the Core Animation Programming Guide.

    0 讨论(0)
  • 2021-01-04 19:27

    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 thinks this makes it a little clearer what's going on and lets you take care of translations in an obvious way, if you have to do them.

    0 讨论(0)
  • 2021-01-04 19:49

    A very concise way of doing this would be:

    CGAffineTransform t = CGAffineTransformMakeScale(1.0 / parentRect.size.width, 1.0 / parentRect.size.height);
    CGRect unitRect = CGRectApplyAffineTransform(rect, t);
    
    0 讨论(0)
提交回复
热议问题