本文介绍了如何在Swift中裁剪UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Swift中编写一个函数,它可以拍摄一个图像并将除了中间的细水平之外的所有内容裁剪掉。我不想保留宽高比。
I want to write a function in Swift that takes an image and crops out everything except a thin horizontal like in the middle. I don't want to preserve the aspect ratio.
这是我到目前为止所做的,但它不能按照我想要的方式工作。我想只保留y = 276到y = 299的像素。
This is what I have so far but it doesn't work the way I want it to. I want to only preserve the pixels from y=276 to 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
}
推荐答案
这个怎么样
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。
EDIT Flipped the CG coordinate to match UIKit.
这篇关于如何在Swift中裁剪UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!