我試圖在互聯網上查找答案并沒有找到它,也許我在互聯網上輸入了錯誤的查詢。
你能告訴我如何裁剪 3:4 的照片嗎?我找不到裁剪它的功能。請分享?
uj5u.com熱心網友回復:
您可以使用此功能以任何縱橫比(例如 3:4)裁剪影像。您必須將您的Image和期望AspectRatio的作為引數傳遞給函式,它將回傳裁剪影像。
func crop(image: UIImage, to aspectRatio: CGFloat) -> UIImage {
let originalAspectRatio = image.size.height/image.size.width
var newImagesize = image.size
if originalAspectRatio > aspectRatio {
newImagesize.height = image.size.width * aspectRatio
} else if originalAspectRatio < aspectRatio {
newImagesize.width = image.size.height / aspectRatio
} else {
return image
}
let center = CGPoint(x: image.size.width/2, y: image.size.height/2)
let origin = CGPoint(x: center.x - newImagesize.width/2, y: center.y - newImagesize.height/2)
let cgCroppedImage = image.cgImage!.cropping(to: CGRect(origin: origin, size: CGSize(width: newImagesize.width, height: newImagesize.height)))!
let croppedImage = UIImage(cgImage: cgCroppedImage, scale: image.scale, orientation: image.imageOrientation)
return croppedImage
}
用法:
let croppedImage = crop(image: "ImageName", to: 3/4)
uj5u.com熱心網友回復:
使用以下功能。有關更多詳細資訊,請閱讀此。
func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage?
{
let imageViewScale = max(inputImage.size.width / viewWidth,
inputImage.size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
y:cropRect.origin.y * imageViewScale,
width:cropRect.size.width * imageViewScale,
height:cropRect.size.height * imageViewScale)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/520179.html
上一篇:怎么把邊框放在圖片里面
下一篇:從for回圈連接通道維度中的影像
