答案 0 :(得分:22)
Swift 3解决方案:
func cropBottomImage(image: UIImage) -> UIImage {
let height = CGFloat(image.size.height / 3)
let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height)
return cropImage(image: image, toRect: rect)
}
使用rect进行裁剪的辅助方法:
func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{
let imageRef:CGImage = image.cgImage!.cropping(to: rect)!
let croppedImage:UIImage = UIImage(cgImage:imageRef)
return croppedImage
}
答案 1 :(得分:8)
这几乎是Alexburtnik的回答
但只是提到UIImage.size是逻辑大小(在"点")
但是,CGImage.cropping()使用了实际尺寸("像素")
因此,如果你使用带有@ 2x或@ 3x修饰符的图像,你会发现 裁剪实际上是预期的一半或三分之一。
因此,当您裁剪时,您可以考虑将矩形乘以"比例"首先是图像的属性,如下所示:
func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? {
var rect = rect
rect.size.width = rect.width * image.scale
rect.size.height = rect.height * image.scale
guard let imageRef = image.cgImage?.cropping(to: rect) else {
return nil
}
let croppedImage = UIImage(cgImage:imageRef)
return croppedImage
}
答案 2 :(得分:0)
方法:
func croppIngimage(ImageCrop:UIImage, toRect rect:CGRect) -> UIImage{
var imageRef:CGImageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, rect)
var croppedimage:UIImage = UIImage(CGImage:imageRef)
return croppedimage
}
致电:
var ImageCrop:UIImage = UIImage(named:"image.png")
答案 3 :(得分:0)
作为UIImage的扩展:
import UIKit
extension UIImage {
func crop(to rect: CGRect) -> UIImage? {
// Modify the rect based on the scale of the image
var rect = rect
rect.size.width = rect.size.width * self.scale
rect.size.height = rect.size.height * self.scale
// Crop the image
guard let imageRef = self.cgImage?.cropping(to: rect) else {
return nil
}
return UIImage(cgImage: imageRef)
}
}
用法:
let myImage = UIImage(named:"myImage.png")
let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
let croppedImage = myImage.crop(to: croppedRect)