Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Crop image for Horizontal Collection Cell imageView
- func cropToBounds(image: UIImage, height: CGFloat, width: CGFloat) -> UIImage {
- let cgimage = image.cgImage!
- var posX: CGFloat = 0.0
- var posY: CGFloat = 0.0
- let contextImage: UIImage = UIImage(cgImage: cgimage)
- let contextSize: CGSize = contextImage.size
- var cgwidth: CGFloat = CGFloat(width)
- var cgheight: CGFloat = CGFloat(height)
- if contextSize.height > contextSize.width {
- cgwidth = contextSize.width * 0.8
- cgheight = contextSize.height * 0.5
- posX = (contextSize.width * 0.1)
- posY = (contextSize.height * 0.2)
- } else if contextSize.width > contextSize.height {
- cgwidth = contextSize.width * 0.8
- cgheight = contextSize.height
- posX = (contextSize.width * 0.1)
- posY = 0
- } else {
- return image
- }
- let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)
- // Create bitmap image from context using the rect
- let imageRef: CGImage = cgimage.cropping(to: rect)!
- // Create a new image based on the imageRef and rotate back to the original orientation
- let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
- return image
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement