Reputation: 239
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.
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.
Upvotes: 1
Views: 87