How can I increase the size of a CGRect by a certain percent value?

后端 未结 7 2024
春和景丽
春和景丽 2021-02-12 14:22

How can I increase the size of a CGRect by a certain percent value? Should I use some form of CGRectInset to do it?

Example:

Assume I have a CGRect:

7条回答
  •  遥遥无期
    2021-02-12 14:41

    You can use CGRectInset if you like:

    double pct = 0.2;
    CGRect newRect = CGRectInset(oldRect, -CGRectGetWidth(oldRect)*pct/2, -CGRectGetHeight(oldRect)*pct/2);
    

    To decrease the size, remove the -s.

    Side note: A CGRect that is 20% bigger than {10, 10, 100, 100} is {0, 0, 120, 120}.


    Edit: If the intention is to increase by area, then this'll do it (even for rectangles that aren't square):

    CGFloat width = CGRectGetWidth(oldRect);
    CGFloat height = CGRectGetHeight(oldRect);
    double pct = 1.2; // 20% increase
    double newWidth = sqrt(width * width * pct);
    double newHeight = sqrt(height * height * pct);
    CGRect newRect = CGRectInset(oldRect, (width-newWidth)/2, (height-newHeight)/2);
    

提交回复
热议问题