This question already has an answer here:
这个问题已经有了答案:
- How do I crop a UIImage in Swift? 2 answers
- 如何用Swift裁剪UIImage ?2答案
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
}
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.
我看过很多不同的指南,但没有一个对我有用。有时候图像会旋转90度,我不知道为什么会这样。
1 个解决方案
#1
15
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
斯威夫特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))
#1
15
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
斯威夫特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))