Code: Select all
UIGraphics.BeginImageContextWithOptions(size, false, ScreenDensity);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
Code: Select all
func scaleCropAndCircleImage(image:UIImage, frame:CGRect) throws -> UIImage {
enum FunctionError: Error {
case nilContext
case nilImage
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(frame.size.width, frame.size.height), false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { throw FunctionError.nilContext }
// width and heights of passed values of uiimage and CGRect
let passedimageWidth = image.size.width
let passedimageHeight = image.size.height
let passedrectWidth = frame.size.width
let passedrectHeight = frame.size.height
// scale factor calculation
let scaleFactorX = passedrectWidth/passedimageWidth
let scaleFactorY = passedrectHeight/passedimageHeight
// centre of the circle calculation
let imageCentreX = passedrectWidth/2
let imageCentreY = passedrectHeight/2
// Creating and clipping to a CIRCULAR Path
let radius = passedrectWidth/2
context.beginPath()
context.addArc(center: CGPoint(x: imageCentreX, y: imageCentreY), radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: false)
context.closePath()
context.clip()
//Seting the scaling factor for graphics context
context.scaleBy(x: scaleFactorX, y: scaleFactorY)
let myRect:CGRect = CGRectMake(0, 0, passedimageWidth, passedimageHeight)
image.draw(in: myRect)
let newCroppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let newCroppedImage else { throw FunctionError.nilImage }
return newCroppedImage
}
Code: Select all
import UIKit
extension UIImage {
func roundedCornerImage(with radius: CGFloat) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = scale
let renderer = UIGraphicsImageRenderer(size: size, format: format)
return renderer.image { rendererContext in
let rect = CGRect(origin: .zero, size: size)
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: .allCorners,
cornerRadii: CGSize(width: radius, height: radius))
path.close()
let cgContext = rendererContext.cgContext
cgContext.saveGState()
path.addClip()
draw(in: rect)
cgContext.restoreGState()
}
}
}