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

后端 未结 7 2013
春和景丽
春和景丽 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:39

    In Swift:

    func increaseRect(rect: CGRect, byPercentage percentage: CGFloat) -> CGRect {
        let startWidth = CGRectGetWidth(rect)
        let startHeight = CGRectGetHeight(rect)
        let adjustmentWidth = (startWidth * percentage) / 2.0
        let adjustmentHeight = (startHeight * percentage) / 2.0
        return CGRectInset(rect, -adjustmentWidth, -adjustmentHeight)
    }
    
    let rect = CGRectMake(0, 0, 10, 10)
    let adjusted = increaseRect(rect, byPercentage: 0.1)
    // -0.5, -0.5, 11, 11
    

    In ObjC:

    - (CGRect)increaseRect:(CGRect)rect byPercentage:(CGFloat)percentage
    {
        CGFloat startWidth = CGRectGetWidth(rect);
        CGFloat startHeight = CGRectGetHeight(rect);
        CGFloat adjustmentWidth = (startWidth * percentage) / 2.0;
        CGFloat adjustmentHeight = (startHeight * percentage) / 2.0;
        return CGRectInset(rect, -adjustmentWidth, -adjustmentHeight);
    }
    
    CGRect rect = CGRectMake(0,0,10,10);
    CGRect adjusted = [self increaseRect:rect byPercentage:0.1];
    // -0.5, -0.5, 11, 11
    

提交回复
热议问题