IOS checks whether a view is within a circle

  ios, question

Check whether there is intersection between the two UIView. I remember that there is an API that can be used directly. Ask for advice

If it is used to judge the view itself, the upstairs method is enough. If it is to judge the intersection problem of rectangle and circle, there are actually some minor complications. I collected some data and packaged a method, which can be directly used in my own project. It is very useful in specific scenarios:

I have encapsulated a code that can be directly used in my own project:

/**
 *  计算任意圆和矩形是否有交集.
 *
 *  @param rect   矩形的边框.
 *  @param center 圆心.
 *  @param r      圆的半径.
 *
 *  @return YES,圆和矩形有交集; NO,圆和矩形无交集.
 */

- (BOOL) boxCircleIntersectWithRect:(CGRect) rect
                             center: (CGPoint) center
                                  r: (double) r
{
    // 初始输入.
    double c[] = {rect.origin.x 加 rect.size.width / 2.0, rect.origin.y 加 rect.size.height / 2.0}; // 矩形中心向量.
    double h[] = {rect.size.width / 2.0, rect.size.height / 2.0};; // 矩形半长向量,即从矩形中心到矩形顶点的向量.
    double p[] = {center.x, center.y}; // 圆心向量.
    
    double v[] = {0, 0}; // 圆心与矩形中心的向量表示.
    double u[] = {0, 0};  // 圆心与矩形最短距离的矢量
    
    // 第一步: 转换至第一象限.
    vDSP_vsubD(c, 1, p, 1, v, 1, 2);
    vDSP_vabsD(v, 1, v, 1, 2);
    
    // 第二步: 求圆心至矩形的最短距离矢量.
    vDSP_vsubD(h, 1, v, 1, u, 1, 2);
    double zero[] = {0.0, 0.0};
    vDSP_vmaxD(u, 1, zero, 1, u, 1, 2);
    
    // 第三步: 长度平方与半径平方比较
    double dotResult = 0.0;
    
    vDSP_dotprD(u, 1, u, 1, &dotResult, 2);
    double powR = pow(r, 2);
    
    BOOL result = (dotResult <= powR );
    
    return result;
}

The inspiration of the algorithm comes from Zhihu, but it is implemented in pseudo code. See:How to judge whether there is overlap between a rectangle and a circle on the plane?
Need to use iOS vector operation related knowledge, can see the CSDN this article:
Matrix and Vector Operations in IOS
For more discussion, see:IOS checks whether a view is within a circle