图片有各种形状和大小。使用 UIImage 的 resize 方法是对图片即时调整大小的灵活方式。以下是一个示例。
let p1: UIImage? = UIImage(named: "img1")
let p2: UIImage? = p1?.resize(toWidth: 300)
let p3: UIImage? = p1?.resize(toHeight: 200)
使用 UIImage 的 crop 方法轻松裁剪图片。下面是一个示例。
let p1: UIImage? = UIImage(named: "img1")
let p2: UIImage? = p1?.crop(toWidth: 400, toHeight: 200)
通过将图片保存到相册,保留这刻的瞬间。以下是一个示例,展示如何裁剪图片并将其保存到设备的相册。
let p: UIImage? = UIImage(named: "img1")
p?.crop(toWidth: 400, toHeight: 200)?.writeToPhotoLibrary()
在保存到相册时,您也可以指定一个目标处理程序。
let p: UIImage? = UIImage(named: "img1")
p?.writeToPhotoLibrary(target: self)
将 Photo Library 保存处理程序添加到目标对象。
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafePointer<Void>) {
let message: String = nil == error ? "Your photo has been saved!" : error!.localizedDescription
let a: UIAlertController = UIAlertController(title: "Status", message: message, preferredStyle: .Alert)
a.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(a, animated: true, completion: nil)
}
您可能需要加载的图片中,并非所有都可以在本地上找到。没关系,使用 UIImage 的 class 方法(contentsOfURL) 可以异步加载远程图片。以下是它的用法示例。
let url: NSURL = NSURL(string: "https://yourimage.io")!
UIImage.contentsOfURL(url) { (image: UIImage?, error: NSError?) in
if let v: UIImage = image {
// do something
}
}
遍历任何 String 中的文本行。以下是一个示例,展示如何在 String 中遍历所有文本行。
let text: String = "This is a\nblock of text\nthat has\nnewlines."
for line in text.lines {
print(line)
}
// output:
// This is a
// block of text
// that has
// newlines.
从文本块的开始和结束处删除空格和换行符。以下是一个示例。
let text: String = " \n Hello World \n "
print(text.trim()) // output: Hello World
获取有用的目录。
print(File.applicationSupportDirectoryPath) // output: ../Application Support/
print(File.documentDirectoryPath) // output: ../Documents/
print(File.libraryDirectoryPath) // output: ../Library/
print(File.cachesDirectoryPath) // output: ../Library/Caches/
轻松在不同的搜索路径中创建目录。
let result: Bool = File.createDirectory("TestDirectory", inDirectory: .DocumentDirectory)
print(result) // output: true
就像创建目录一样简单,删除它也同样简单。
let result: Bool = File.removeDirectory("TestDirectory", inDirectory: .DocumentDirectory)
print(result) // output: true