如何在Swift中裁剪UIImage?

我想在Swift中编写一个函数,它会拍摄一张图像,然后剪出除了像中间一样细的水平线以外的所有东西。 我不想保留宽高比。

这是我迄今为止,但它不工作,我想要的方式。 我只想保留从y = 276到y = 299的像素。

func cropImageToBars(image: UIImage) -> UIImage { let rect = CGRectMake(0, 200, image.size.width, 23) UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage 

}

你的代码做这个倒退。 UIImage drawInRect()方法将整个图像绘制到目标矩形中。 把它想象成电影放大器或幻灯机。 您可以调整渲染图像的框的大小和形状。 你设置了一个图像上下文,就像一块能够捕捉图像的电影。

您通常想要将图像渲染为图像的全尺寸的矩形,并将其原点移位,以便原点为0的图像上下文捕获图像的所需位。

我有一个名为CropImg的演示项目,演示如何裁剪图像的一部分。 它有一个用户界面,让用户select图像的一部分。 你的情况更简单,但它应该给你的想法。

这个怎么样

 func cropImageToBars(image: UIImage) -> UIImage { let rect = CGRectMake(0, 200, image.size.width, 23) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) defer{ UIGraphicsEndImageContext() } flipContextVertically(rect.size) let cgImage = CGImageCreateWithImageInRect(image.CGImage, rect)! return UIImage(CGImage: cgImage) } func flipContextVertically(contentSize:CGSize){ var transform = CGAffineTransformIdentity transform = CGAffineTransformScale(transform, 1, -1) transform = CGAffineTransformTranslate(transform, 0, -contentSize.height) CGContextConcatCTM(UIGraphicsGetCurrentContext(), transform) } 

编辑翻转CG坐标以匹配UIKit。