maw*_*nch 13 crop uiimage ios swift
我正在编写一个带有图像的应用程序,除了图像中心的矩形外,还可以裁剪掉所有内容.(SWIFT)我无法让裁剪功能起作用.这就是我现在拥有的:
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
}
Run Code Online (Sandbox Code Playgroud)
我看了很多不同的指南,但似乎没有一个对我有用.有时图像旋转90度,我不知道它为什么这样做.
ped*_*uan 26
如果您想使用扩展程序,只需将其添加到文件中,开头或结尾即可.您可以为此类代码创建额外的文件.
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))
Run Code Online (Sandbox Code Playgroud)
用于图像中心部分的裁剪:
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13502 次 |
| 最近记录: |