在Swift中裁剪UIImage的问题 [英] Problems with cropping a UIImage in Swift

查看:147
本文介绍了在Swift中裁剪UIImage的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,该应用程序可以拍摄图像并裁剪掉除图像中心的矩形以外的所有内容。 (SWIFT)但是我无法启用裁剪功能。这就是我现在拥有的东西:

I'm writing an app that takes an image and crops out everything except for a rectangle in the center of the image. (SWIFT) I can't get the crop function to work though. This is what I have now:

func cropImageToBars(image: UIImage) -> UIImage {
     let crop = CGRectMake(0, 200, image.size.width, 50)

     let cgImage = CGImageCreateWithImageInRect(image.CGImage, crop)
     let result: UIImage = UIImage(CGImage: cgImage!, scale: 0, orientation: image.imageOrientation)

     UIImageWriteToSavedPhotosAlbum(result, self, nil, nil)

     return result
  }

我看过很多不同的指南,但它们似乎都不适合我。有时图像会旋转90度,我不知道为什么会这样做。

I've looked at a lot of different guides but none of them seem to work for me. Sometimes the image is rotated 90 degrees, I have no idea why it does that.

推荐答案

如果您想使用扩展名,只需将其添加到文件的开头或结尾即可。您可以为此类代码创建一个额外的文件。

If you would like to use an extension, just simply add it to the file, in the beginning, or the end. You can create an extra file for such code.

Swift 3.0

extension UIImage {
    func crop( rect: CGRect) -> UIImage {
        var rect = rect
        rect.origin.x*=self.scale
        rect.origin.y*=self.scale
        rect.size.width*=self.scale
        rect.size.height*=self.scale

        let imageRef = self.cgImage!.cropping(to: rect)
        let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
        return image
    }
}


let myImage = UIImage(named: "Name")
myImage?.crop(rect: CGRect(x: 0, y: 0, width: 50, height: 50))

用于裁剪图像的中心部分:

for crop of a center portion of an image:

let imageWidth = 100.0
let imageHeight = 100.0
let width = 50.0
let height = 50.0
let origin = CGPoint(x: (imageWidth - width)/2, y: (imageHeight - height)/2)
let size = CGSize(width: width, height: height)

myImage?.crop(rect: CGRect(origin: origin, size: size))

这篇关于在Swift中裁剪UIImage的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆