0

I have center points and radius of circle, I just wanna get all CGPoint that the area of the circle covers. Basically I need to get all pixels through these CGPoint, I have a code for getting pixel from UIImage through CGPoint. I'm getting center points of circle through UITapGestureRecognizer when user tap. And I already know about radius of circle.

Can anyone tell me how I can get all CGPoint or pixels from circle. Thanks

For Example Origin of below circle is CGPoint(x: 206, y: 105), and diameter of a circle is 50.

enter image description here

Another Example How I can get these all CGPoints

enter image description here

ZAFAR007
  • 3,049
  • 1
  • 34
  • 45

1 Answers1

1

First, You get minX and minY maybe in radius from center.

Second, check point by point and calculate distance to center.

func distance(from: CGPoint, to: CGPoint) -> CGFloat {
  return CGFloat(sqrt((from.x - to.x)*(from.x - to.x) + (from.y - to.y)*(from.y - to.y)))
}

func isInCircle(withCenter center: CGPoint, point: CGPoint, radius: CGFloat) -> Bool {
  return distance(from: center, to: point) <= radius
}

func getPoints(withCenter center:CGPoint, radius: CGFloat) -> [CGPoint] {
  let minX = Int(center.x - radius)
  let minY = Int(center.y - radius)
  let maxX = Int(center.x + radius)
  let maxY = Int(center.y + radius)

  var result = [CGPoint]()
  for x in minX...maxX {
    for y in minY...maxY {
      let point = CGPoint(x: x, y: y)
      if isInCircle(withCenter: center, point: point, radius: radius) {
        result.append(point)
      }
    }
  }

  return result
}


let x = getPoints(withCenter: CGPoint.init(x: 206, y: 150), radius: 50)
print(x)
Thanh Vu
  • 1,599
  • 10
  • 14
  • 1
    `distance` can be simplified to merely `return hypot(from.x - to.x, from.y - to.y)`. – Rob Sep 03 '19 at 03:56