首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何裁剪图像3:4?斯威夫特

如何裁剪图像3:4?斯威夫特
EN

Stack Overflow用户
提问于 2022-10-25 10:04:51
回答 2查看 51关注 0票数 2

我试着在网上查找答案,但没有找到,也许我在网上打错了我的查询。

你能告诉我怎么剪一张3:4的照片吗?我找不到裁剪它的功能。请分享?

EN

回答 2

Stack Overflow用户

发布于 2022-10-25 11:23:58

您可以使用此函数在任何AspectRatio (例如3:4)中裁剪图像。您必须将您的Image和所需的AspectRatio作为参数传递给函数,它将返回裁剪后的图像。

代码语言:javascript
复制
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
}

使用:

代码语言:javascript
复制
 let croppedImage = crop(image: "ImageName", to: 3/4)
票数 2
EN

Stack Overflow用户

发布于 2022-10-25 10:25:05

使用以下函数。欲知更多细节,请阅读

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74192346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档