Search code examples
iosobjective-cswiftgeometrycore-graphics

insetBy returns Inf in CGRect


I am using insetBy of CGGeometry, but it returns inf as value for x and y.

CGGeometry

public func insetBy(dx: CGFloat, dy: CGFloat) -> CGRect

Below is my code with output :

    let frame = CGRect(x: xOffset[row], y: yOffset[row], width: width, height: height)
    print(frame)     //(0.0, 0.0, 54.0, -3.0)

    let insetFrame = frame.insetBy(dx: 4.0, dy: 2.0)
    print(insetFrame)   //(inf, inf, 0.0, 0.0)

This frame cause crash in application. Any help should be appreciated.


Solution

  • Negative width/height doesn't make sense and it obviously breaks the CGRect calculations.

    Just don't use negative values for width and height and you'll be fine:

    let frame = CGRect(x: xOffset[row], y: yOffset[row], width: max(8, width), height: max(4, height))
    

    You can define some maxInsetX and maxInsetY constant, to be sure that your initial frames will never be smaller than 2*maxInset in both dimensions.