1

I want to draw a rotated rectangle on a UIImage where rotation will be based on a given center. My concept is to select starting coordinate of the rectangle first, then calculate the new coordinate of the point after rotation based on the center, then draw on the UIImage. The program is given below, which is doing perfectly when the angle is 0 degrees, but unfortunately, the rectangle is not placed perfectly when rotation occurs. Placed exact location when no rotation (Angle: 0 degree) Slightly changed when 10 degree rotation

func drawRotatedRectangleOnImage(image: UIImage, angle: Angle) -> UIImage? {
    let size = image.size
    UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
    guard let context = UIGraphicsGetCurrentContext() else {
        return nil
    }
    let point = convertedPointOfRectangle(sizeOfFgImage: size)
    let rect = CGSize(500, 500)
    context.rotate(by: angle.radians)
    context.setFillColor(UIColor.gray.cgColor)
    context.fill(CGRect(x: point.x, y: point.y, width: rect.width, height: rect.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    
    UIGraphicsEndImageContext()
    
    return newImage
}


func convertedPointOfRectangle(sizeOfFgImage : CGSize, angle: Angle) -> CGPoint {
    
    let size = DripContainerViewSize
    let point = CGPoint(0, 0) // starting point of the rectangle
    let center = CGPoint(x: 300, y: 300) // center for rotation
    let res = rotatePoint(center: center, point: CGPoint(x: pointX, y: pointY), angle: angle.radians)
    return res // after rotation, the position of the starting point
    
}

func rotatePoint(center: CGPoint, point: CGPoint, angle: Double) -> CGPoint {
    
    let x = (point.x - center.x) * cos(angle) + (point.y - center.y) * sin(angle) + center.x
    let y = (point.y - center.y) * cos(angle) - (point.x - center.x) * sin(angle) + center.y
    
    return CGPoint(x: x, y: y)
}

I am a beginner in swift and looking for the error I made in these functions as well as the solution.

Jabed Dhali
  • 167
  • 6
  • Unclear what the goal is. "draw a rotated rectangle on a UIImage where rotation will be based on a given center" is unclear. Can you explain better? Feel free to employ pictures. – matt Mar 02 '23 at 13:30
  • Okay, so you are way overthinking this! You _can_ do it the way you want to do it, more or less, but there is no need. Rotation is around the center automatically. Don't calculate anything. Just work out where the unrotated rectangle should go and draw it there with a rotation transform. This method will help you a _lot:_ https://developer.apple.com/documentation/uikit/uibezierpath/1624340-apply – matt Mar 02 '23 at 13:54
  • Actually I want to rotate the rectangle based on the given center, not on the center of the rectangle. How can I change the center of rotation? – Jabed Dhali Mar 02 '23 at 13:58

0 Answers0