我正在处理要裁剪图像的应用程序。
目前,这是我的裁剪方式:
mainPicture.layer.cornerRadius = mainPicture.frame.size.width / 2
mainPicture.clipsToBounds = true
请求不是从中间裁剪,而是在特定半径和顶部12 px范围内裁剪。
当我当前修剪时,它只是从中间修剪,所以结果是这样的:
请求是对其进行裁剪,以使圆的顶部距顶部12 px:
这样最终的图像将如下所示:
如何使用Swift 4.0做到这一点?
答案 0 :(得分:3)
这里您需要做的是首先将原始图像从顶部裁剪为具有所需边距的正方形图像(例如20),然后将图像设置为“图像”视图。
以下是您可以在UIImage
类上编写的用于裁剪的扩展名:
extension UIImage {
func getCroppedImage(with topMargin: CGFloat) -> UIImage? {
let heightWidth = size.height < size.width ? size.height : size.width
let x = (size.width - heightWidth)/2
let rect = CGRect(x: x, y: topMargin, width: heightWidth, height: heightWidth)
if let imageRef = cgImage?.cropping(to: rect) {
return UIImage(cgImage: imageRef)
}
return nil
}
}
然后在将图像设置为UIImageView
之前,请为您的图像调用此方法,例如:
let image = UIImage(named: "test")
imageView.image = image?.getCroppedImage(with: 20)
输出:
这是输入图像:
这是输出:
答案 1 :(得分:1)
通过使用此功能发布图像之前裁剪图像来修复它:
func cropToBounds(image: UIImage, width: CGFloat, height: CGFloat) -> UIImage {
let cgimage = image.cgImage!
let contextImage: UIImage = UIImage(cgImage: cgimage)
let contextSize: CGSize = contextImage.size
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
var cgwidth: CGFloat = width
var cgheight: CGFloat = height
// See what size is longer and create the center off of that
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = (( contextSize.width - contextSize.height) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
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
}