How can I rotate an image drawn by CGContextDrawImage() at its center?
In drawRect:
CGContextSaveGState(c);
rect = CGRectO
This function can draw image on an existing image with rotation angle in radians.
Swift 3:
extension UIImage {
func putImage(image: UIImage, on rect: CGRect, angle: CGFloat = 0.0) -> UIImage{
let drawRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(drawRect.size, false, 1.0)
// Start drawing self
self.draw(in: drawRect)
// Drawing new image on top
let context = UIGraphicsGetCurrentContext()!
// Get the center of new image
let center = CGPoint(x: rect.midX, y: rect.midY)
// Set center of image as context action point, so rotation works right
context.translateBy(x: center.x, y: center.y)
context.saveGState()
// Rotate the context
context.rotate(by: angle)
// Context origin is image's center. So should draw image on point on origin
image.draw(in: CGRect(origin: CGPoint(x: -rect.size.width/2, y: -rect.size.height/2), size: rect.size), blendMode: .normal, alpha:
1.0)
// Go back to context original state.
context.restoreGState()
// Get new image
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
If you need to create and empty image with size and color, use:
extension UIImage {
convenience init?(size: CGSize, color: UIColor) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 1.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}